Ejemplo n.º 1
0
def LOGIN_INSECURE(un="",pw=""):
    global r, user_string, loaded_username
    if un != "" and pw != "":
        # CLI LOGIN
        EMAIL, PASSWD = un, pw
    elif un == "" and pw == "":
        # CREDS FILE
        if not os.path.isfile(CREDENTIALSFILE):
            errext(1, f"Credentials file missing in current path '{CREDENTIALSFILE}'. Follow README.md for creation instructions.")
        with open(CREDENTIALSFILE) as f:
            lines = base64.b64decode(f.read()).decode("utf-8").split()
        # lines = open("creds").readlines() # much less secure (creds file has 3 lines, email/username, password)
        EMAIL, PASSWD = map(lambda x: x.strip(), lines)
    else:
        # FAIL
        errext(1, "If using CLI arguments for insecure login, must specify: username and password.")
    # now we have creds, login in and such
    loaded_username = EMAIL
    user_string = EMAIL.split("@")[0] # get the username part of the email (or just the username if username was provided)
    # probably don't need this try block but it doesn't hurt - so we logout first
    try:
        r.logout()
    except:
        pass
    # login and don't store session to pickle file, so that we
    login = r.login(EMAIL, PASSWD, expiresIn = expires_seconds, store_session=False) # changed to store_session false so could load gabes data
    return login
Ejemplo n.º 2
0
def robinbot(buy, sell):
    totp = pyotp.TOTP(config.robin_totp).now()
    print("Current OTP: ", totp)
    login = robin_stocks.login(config.robin_user, config.robin_pwd, mfa_code=totp)

    holdings = robin_stocks.get_open_stock_positions()
    print(buy)
    print(sell)
    for stock in sell:
        stock = stock.strip()
        if stock in holdings:
            quantity = holdings[stock]["quantity"]
            robin_stocks.order_sell_fractional_by_quantity(stock, quantity, 'gfd')

    acc = robin_stocks.load_account_profile()
    print(acc)
    bp = acc["portfolio_cash"]
    print(bp)
    bp = float(bp)
    if bp > 0:
        bpps = bp/len(buy)
        print(bpps)
        for stock in buy:
            order = robin_stocks.order_buy_fractional_by_price(stock, bpps, 'gfd')
            print(order)
    else:
        print("not enough buying power")
    robin_stocks.logout()
Ejemplo n.º 3
0
    def logout(self):
        """
        Method to logout of current robinhood session

        :param: None
        :return: None
        """
        logging.info('logging out of robinhood...')
        api.logout()
Ejemplo n.º 4
0
def main():
    # remove the store_session= false to ignore login everytime
    # login = r.login("*****@*****.**", "Warriors_123", store_session=False)
    login = r.login("*****@*****.**", "Warriors_123")
    if not login:
        sys.exit(1)

    while True:
        try:
            start()
            time.sleep(15)
        except KeyboardInterrupt:
            print("\n Thank you for using us...")
            r.logout()
            break
Ejemplo n.º 5
0
def import_orders():
    # TODO: Check if logged in
    # get all orders (assumed logged in)
    orders = r.get_all_stock_orders()

    r.logout()

    clean_orders = []
    for order in orders:
        # filled = float(order['cumulative_quantity'])
        if len(order['executions']) > 0:
            instrument = r.helper.request_get(order['instrument'])
            symbol = instrument['symbol']
            side = order['side']
            fees = order['fees']
            price = order['average_price']
            #         quantity = order['quantity'] # intented quantity for order
            quantity = order['cumulative_quantity']  # filled quantity
            timestamp = order['created_at']
            clean_orders.append({
                'Timestamp': timestamp,
                'Symbol': symbol,
                'Quantity': quantity,
                'Price': price,
                'Side': side.upper(),
                'Commission': 0.0,
                'Fee': fees,
                'Type': 'SHARE'
            })

    rh_executions = pd.DataFrame(clean_orders,
                                 columns=[
                                     'Timestamp', 'Symbol', 'Quantity',
                                     'Price', 'Side', 'Commission', 'Fee',
                                     'Type'
                                 ])

    # import data
    importer = GenericImporter()
    importer.load_dataframe(rh_executions)
    update_results = importer.import_data()

    return update_results
Ejemplo n.º 6
0
def login():
    if not ('username' in request.json and 'password' in request.json):
        return 'Invalid Request', 400

    if 'mfa_code' in request.json:
        login = robinhood.login(request.json['username'],
                                request.json['password'],
                                mfa_code=request.json['mfa_code'],
                                store_session=False)
    else:
        login = robinhood.login(request.json['username'],
                                request.json['password'],
                                store_session=False)
    response = {}
    response['access_token'] = login['access_token']
    response['expires_in'] = login['expires_in']
    robinhood.logout()
    del login
    return response, 200
Ejemplo n.º 7
0
def run():
    f.add_event_log('function[run] Robinhood Auto_trader Start')

    market: str = find_variable('market')
    symbol: str = find_variable('symbol')
    # check if market is currently open
    f.add_event_log('function[run] Market Open: {0}'.format(
        f.is_market_open(market)))

    if f.is_market_open(market):
        f.add_event_log('function[run] Market Open')

        # login
        f.account_login()
        # check spread positions
        if 1 > len(rs.get_open_option_positions()):
            purchase(symbol)

        portfolio_credit_spreads: list[
            CreditSpread] = f.get_credit_spreads_portfolio()

        # if list is empty place an order && sufficient balance

        # check age of the spreads
        for credit_spread in portfolio_credit_spreads:
            f.add_event_log('function[run] Check purchase date')
            purchase_date = d.datetime.strptime(credit_spread.purchase_date,
                                                '%Y-%m-%d')
            if (d.datetime.today() - purchase_date).days >= 30:
                f.add_event_log(
                    'function[run] purchase_date: {0} is older than 30 day. Sell position.'
                )
                f.sell_loop(credit_spread)

        # check update config file
        if len(portfolio_credit_spreads) > 0:
            # stop_loss
            f.stop_loss(portfolio_credit_spreads, market)
        # log out
        rs.logout()
        f.add_event_log('function[run] Account Logout')
    f.add_event_log('function[run] Robinhood Auto_trader Shutdown.')
Ejemplo n.º 8
0
 def get(self):
     r.logout()
     return {}
Ejemplo n.º 9
0
 def logout(self):
     logout = rs.logout()
     self.auth_token = None
     return logout
Ejemplo n.º 10
0
 def Logout(self):
     try:
         rs.logout()
     except Exception as e:
         raise StockAPIException(e)
Ejemplo n.º 11
0
 def logout(self):
     robin_stocks.logout()
Ejemplo n.º 12
0
import robin_stocks as rs
import os

# Assuming login info is set in environment:
rs.authentication.login(os.environ.get("robinhood_username"),
                        os.environ.get("robinhood_password"))

portfolio = rs.account.build_holdings(with_dividends=True)

print("Ticker   Qty Shares  Equity")
for x in portfolio:
    print(x, "  ", portfolio[x].get("quantity"), "  ",
          portfolio[x].get("equity"))

rs.logout()
Ejemplo n.º 13
0
 def get_market_value(self):
     login = r.login(self.username, self.password)
     btc_info = r.get_crypto_quote('BTC')
     login = r.logout()
     return btc_info['mark_price']
Ejemplo n.º 14
0
 def teardown_class(cls):
     r.logout()
Ejemplo n.º 15
0
        seconds += 1
# {"SHOP":{price:500, price_bought:525, shares_quant:}}
#
# SHOP [500, 501,502, 505, 505, 510, 499, 501]
#

def BUY():
    fdsf

def SELL():
    es;krer

def HOLD():
    sdfls;k 

robin.logout()


def perform_ta(i, period=15):
    if (i-period < 0):
        start = 0
    else:
        start = i + 1 - period

    end = i + 1
    data = TA_LIST[start:end] 
    cleaned_data = []
    for x in data:
        if x != -1:
            cleaned_data.append(x)
        else:
def stop_loss(credit_spread: list[CreditSpread], market: str):
    # stop loss continue loop while market is open and current price is below stop
    keep_watch: bool = True
    add_event_log('function[stop_loss] Starting Market Watch.')
    # make a list of objects to iterate through
    while keep_watch:
        # continue monitoring price while market is open with open positions
        if is_market_open(market) and len(credit_spread) > 0:

            for i in range(len(credit_spread)):
                # Credit Spread Long Price
                long_current = get_current_price(credit_spread[i],
                                                 credit_spread[i].buy_strike)
                # Credit Spread Short Price
                short_current = get_current_price(credit_spread[i],
                                                  credit_spread[i].sell_strike)
                # Current Spread Value
                price_current: float = round(short_current - long_current, 2)
                price_stop: float = round(credit_spread[i].stop_value, 2) / 100
                # stop loss
                if price_current >= price_stop:
                    add_event_log('function[stop_loss] Enacting Stop Loss')
                    # sell the spread
                    sell_loop(credit_spread[i])
                    credit_spread.pop(i)
                # TODO ADJUST TAKE PROFIT
                take_profit: float = (credit_spread[i].spread_value *
                                      .25) / 100
                if take_profit >= price_current:
                    add_event_log('function[stop_loss] Beginning Take Profit')
                    while price_current >= (credit_spread[i].spread_value *
                                            .75):
                        cancel = sell_credit_spread(
                            credit_spread[i].symbol, credit_spread[i].quantity,
                            take_profit, credit_spread[i].expiration_date,
                            credit_spread[i].sell_strike,
                            credit_spread[i].buy_strike,
                            credit_spread[i].option_type)
                        rs.logout()
                        time.sleep(60)
                        account_login()
                        open_positions = Enumerable(
                            rs.get_all_open_option_orders()).where(
                                lambda x: x['state'] == 'queued')
                        if len(open_positions) > 0:
                            rs.helper.request_post(cancel)
                            long_current = get_current_price(
                                credit_spread[i], credit_spread[i].buy_strike)
                            short_current = get_current_price(
                                credit_spread[i], credit_spread[i].sell_strike)
                            price_current = round(short_current - long_current,
                                                  2)
                add_price_log(credit_spread[i].symbol,
                              credit_spread[i].expiration_date,
                              credit_spread[i].buy_strike,
                              credit_spread[i].sell_strike, long_current,
                              short_current, price_current, price_stop,
                              take_profit)
            rs.logout()
            add_event_log('function[stop_loss] Account Logout')
            time.sleep(120)
            account_login()

        else:
            keep_watch = False
    add_event_log('function[stop_loss] Exiting Market Watch')
Ejemplo n.º 17
0
 def logout(self):
     print('Logging you out.')
     r.logout()
Ejemplo n.º 18
0
    def __init__(self, username, password):

        ## Data structure set up:

        self.running = True

        # Account specific
        self.username = username
        self.password = password

        # Totals and instance specific
        self.up_since = time.time()
        self.starting_total_value = None
        self.total_value = 0
        self.total_trades = 0
        self.total_stops_losses = 0
        self.total_take_profits = 0

        # Symbol specific
        self.quote = defaultdict(float)  # Current price
        self.quantity_on_hand = defaultdict(float)
        self.cost_basis = defaultdict(float)
        self.buy_price = smartdict(
            lambda k: self.cost_basis[k] / self.quantity_on_hand[k])
        self.symbol_value = defaultdict(float)  # Value in usd
        self.symbol_pnl_percent = defaultdict(float)

        self.symbol_trades = defaultdict(int)
        self.symbol_take_profits = defaultdict(
            int)  # How many take profits triggered
        self.stop_losses_triggered = defaultdict(
            int)  # How many stops triggered
        self.rsi = defaultdict(float)
        self.time_rsi_cutoff_last_adjusted = defaultdict(lambda: self.up_since)

        self.take_profit_percent = TAKE_PROFIT_PERCENT
        self.stop_loss_percent = STOP_LOSS_PERCENT
        self.cost_quote = smartdict(lambda k: 0 if self.quantity_on_hand[
            k] == 0 else self.cost_basis[k] / self.quantity_on_hand[k])
        self.stop_loss_quote = smartdict(lambda k: self.cost_quote[k] * (
            100 - self.stop_loss_percent[k]) / 100)
        # self.stop_loss_delta = smartdict(lambda k: self.quote[k] - self.stop_loss_quote[k])
        self.stop_loss_delta = smartdict(
            lambda k: self.cost_quote[k] - self.stop_loss_quote[k])

        # Can be a number or dict
        self.starting_rsi_buy_at = RSI_BUY_AT
        self.starting_rsi_sell_at = RSI_SELL_AT
        # for current levels
        self.rsi_buy_at = smartdict(self.starting_rsi_buy_at)
        self.rsi_sell_at = smartdict(self.starting_rsi_sell_at)
        self.rsi_step_buy_when_triggered = RSI_STEP_BUY_WHEN_TRIGGERED
        self.rsi_step_sell_when_triggered = RSI_STEP_SELL_WHEN_TRIGGERED
        self.rsi_reset_buy_speed = RSI_RESET_BUY_SPEED
        self.rsi_reset_sell_speed = RSI_RESET_SELL_SPEED

        # How many digit of precision allowed by robinhood
        self.ndigits = defaultdict(int)  # {symbol : increment (int)}
        self.ndigits['ETC'] = 6
        self.ndigits['ETH'] = 6
        self.ndigits['BTC'] = 8
        self.ndigits['DOGE'] = 0
        self.ndigits['LTC'] = 8

        # holds active orders placed
        self.order_ids = dict()  # {time : id} pairs

        ## Arguments
        global DEBUG
        if "--debug" in sys.argv:
            DEBUG = True

        ## Actions performed on start up:

        # Login
        rh.login(username=username,
                 password=password,
                 expiresIn=86400,
                 by_sms=TWO_FACTOR_IS_SMS)
        rh.logout()
        rh.login(username=username,
                 password=password,
                 expiresIn=86400,
                 by_sms=TWO_FACTOR_IS_SMS)
        # Load orders that may have been placed before this program started
        self.load_active_crypto_orders()
        self.quantity_on_hand['USD'] = self.check_cash_on_hand()

        ## Set up the display
        self.disp_heading = Display()
        self.disp_grid_heading = Display(
            "Sym\tQuote\tStop\tQty\tVal\tPnL\tCost\tRSI\tBuy@\tSell@\tT|P|L\tTP|SL"
        )
        self.disp_usd = Display(num_lines=1)
        self.disp_crypto = Display(num_lines=len(SYMBOLS))
        self.disp_totals = Display(num_lines=1)
        self.disp_info_feed = TimedDisplay(num_lines=8)
        self.disp_info_feed.set_logger('disp_info_log')

        self.disp_warn_feed = TimedDisplay(disappear_time=360, num_lines=4)
        self.disp_warn_feed.set_logger('warn_info_log')

        self.disp_combo_feed = CombinedDisplay(self.disp_info_feed,
                                               self.disp_warn_feed)

        self.display = ConsoleInterface(self.disp_heading,
                                        self.disp_grid_heading, self.disp_usd,
                                        self.disp_crypto, self.disp_totals,
                                        self.disp_combo_feed)

        ## DEBUG
        if DEBUG:
            with open("account-data.log", 'w') as f:
                for line in pformat(rh.load_phoenix_account(), indent=4):
                    f.write(line)
def click_logout():
    rs.logout()
Ejemplo n.º 20
0
        basket,
        cash=10000,
        indicators=[Moving_Average(n=200),
                    Moving_Average(n=10),
                    RSI(2)])
    # get model
    from models import Mean_Reversion
    mr = Mean_Reversion('Mean Reversion', 200, 10, 2)
    # build investor
    from investor import Investor
    i = Investor(models=[mr], world=w, live=False)
    # set up backtest
    from backtest import Backtest
    b = Backtest(name='mean_reversion_backtest_000', investor=i, base_world=w)
    # show/export results
    b.do_backtest()
    b.export_history(path='backtests/')

    # --- workflow 4 ---

    # neural ODE model class / some other trainable model
    # that will allow us to good make use of the backtesting tools

    # --- workflow 5 ---

    # exporting, importing model
    # test many models against each other
    # export best ones

    r.logout()
Ejemplo n.º 21
0
import robin_stocks
from robin_stocks import *
robin_stocks.login("*****@*****.**", "sariadirowi")
my_stocks = robin_stocks.build_holdings()
for key, value in my_stocks.items():
    print(key, value)

optionData = robin_stocks.find_options_for_list_of_stocks_by_expiration_date(
    ['ba', 'ccl'], expirationDate='2020-04-17', optionType='put')
for item in optionData:
    print(' price -', item['strike_price'], ' exp - ', item['expiration_date'],
          ' symbol - ', item['chain_symbol'], ' delta - ', item['delta'],
          ' theta - ', item['theta'])

robin_stocks.logout()
Ejemplo n.º 22
0
 def test_login_failed(self):
     r.logout()
     profile = r.load_account_profile(info=None)
     assert profile
Ejemplo n.º 23
0
                                 n1=10,
                                 n2=20,
                                 days=6,
                                 direction="above")
            if (cross == 1):
                potential_buys.append(symbol)
    if (len(potential_buys) > 0):
        print("\n----- There are: " + str(len(potential_buys)) +
              " potential buys in the watchlist -----\n")
        print(potential_buys)
        answer = input("\nWould you like to make a buy order (yes or no):")
        if answer == "yes":
            buy_holdings(potential_buys, profile_data, holdings_data)
            print("\n----- Buy order has been excecuted -----\n")
        elif answer == "no":
            print("\n----- Buy order has been terminated -----\n")
        else:
            print("\nPlease enter yes or no.")
    if (len(sells) > 0):
        update_trade_history(sells, holdings_data, "tradehistory.txt")

    print("----- Scan over -----\n")


#execute the scan
scan_stocks()

print("----- Logging out -----\n")
#Log in to Robinhood
logout = r.logout()
Ejemplo n.º 24
0
 def killBot(self, sig, frame):
     print('Exiting...')
     r.logout()
     sys.exit(0)
Ejemplo n.º 25
0
 def get_historical(self):
     login = r.login(self.username, self.password)
     btc_history = r.crypto.get_crypto_historical('BTC', '5minute', 'day', '24_7')
     login = r.logout(); 
     return btc_history