def calculate_balances(): logging.info('Looking up current balances...') # Calculate our on hand cash and the ETH amount: try: cash_on_hand = r.load_account_profile()['crypto_buying_power'] except: logging.info('Issue determining buying power') try: crypto_to_sell = float( r.get_crypto_positions()[0]['quantity_available']) except: logging.info( 'Problem determining {} amount on hand'.format(crypto_symbol)) # Calculate an open_position flag: open_position = True if crypto_to_sell > 0 else False open_position # Save to a dictionary and return: current_balances = { 'cash_on_hand': float(cash_on_hand), 'crypto_to_sell': float(crypto_to_sell), 'open_position': open_position } return current_balances
def get_cash(self): logging.info('Getting actual cash value...') profile = robin_stocks.load_account_profile() self.portfolio_cash = round(float(profile['portfolio_cash']), 2) self.buying_power = round(float(profile['buying_power']), 2) self.cash = round(float(profile['cash']), 2) self.unsettled_funds = round(float(profile['unsettled_funds']), 2) self.unsettled_debit = round(float(profile['unsettled_debit']), 2) self.cash_held_for_collateral = round( float(profile['cash_held_for_options_collateral']), 2) logging.info('Getting cash deposited/withdrawn...') transfers = robin_stocks.get_bank_transfers() for transfer in transfers: if transfer[ 'cancel'] is not None or transfer['state'] != 'completed': continue amount = round(float(transfer['amount']), 2) fees = round(float(transfer['fees']), 2) event_time = utc_to_eastern(transfer['created_at']) if transfer['direction'] == 'deposit': logging.info( f'Adding deposit of ${amount} with a fee of {fees} at {event_time.isoformat()}' ) self.total_deposited += round(amount - fees, 2) else: logging.info( f'Adding withdrawl of ${amount} with a fee of {fees} at {event_time.isoformat()}' ) self.total_withdrawn += round(amount + fees, 2)
def allocate_cash(buy_list): """ checks how much cash to allocate and whether there is space. Best stocks reported first so we always go through them first. If not enough cash, then we don't buy. returns a dicitonary of new buys {ticker: [date, amount, price]} """ my_holdings = r.account.build_holdings() # get holdings portfolio_cash = None user_profile = r.load_account_profile() for key, value in user_profile.items(): if key == 'portfolio_cash': portfolio_cash = float(value) break new_buys = {} f.write("Portfolio cash: " + str(portfolio_cash) + '\n') for stock in buy_list: if stock[1] in my_holdings.keys(): continue # skip because we already own this stock price = float(r.stocks.get_latest_price(stock)[0]) if float(portfolio_cash) // float(price) < 1: continue ## we don't have enough money to trade else: max_amount_willing = (1/3)*portfolio_cash # willing to give 1/3 of the account to one position to_buy = max_amount_willing // price # returns number of shares to buy if to_buy >= 1: date_bought = buy_stock(stock[1], to_buy) if date_bought != False: new_buys[stock[1]] = [date_bought, to_buy, price] portfolio_cash -= to_buy*price return new_buys # returns a dict with stock: date, amount, price
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()
def sign_in(): """ Sign in to RobinHood to access data when server starts up :return: None """ try: try: rbh.load_account_profile() except Exception as e: totp = pyotp.TOTP('My2factorAppHere').now() login = rbh.login(username, password, mfa_code=totp) print('sign in successfully') return login except Exception as e: print('fail login') print(e)
def info(fetch): print(f'\nFetching {fetch}....\n') result = rh.load_account_profile() if fetch is not None: ui.success(result[fetch]) else: ui.success(result)
def __init__(self): with open("robinhood", "r", newline="\n") as file: username, password = file.read().strip().split("\n") r.login(username=username, password=password) cash = float(r.load_account_profile("cash")) super().__init__(cash) holdings = r.build_holdings() for symbol in holdings.keys(): holding = holdings[symbol] self.tickets[symbol] = float(holding["quantity"])
def account_info(): # Get account information. account = rs.load_account_profile() print('\n') pprint(account) # Check if account is restricted from trading. if account['deactivated']==True: print('Account is currently restricted from trading.') # Check Cash Balance. print('\n${} is available as Cash Balance.'.format(account['buying_power'])) print('\n${} is Held as Options Collateral.'.format(account['margin_balances']['cash_held_for_options_collateral']))
def getCash(self): reserve = 0.00 try: me = r.load_account_profile() cash = float(me['portfolio_cash']) except: print("Issue retrieving cash on hand amount") return -1.0 if cash - reserve < 0.0: return 0.0 else: return cash - reserve
def load_account_profile( t: datetime, online: bool, log: bool ) -> AccountProfile: """ Loads user profile information from Robinhood including total equity, cash, and dividend total. """ resp: Dict[str, Any] = {} account_profile_base_dir: str = os.path.join("data", "account_profile") account_profile_output_dir: str = os.path.join( account_profile_base_dir, t.strftime("%Y"), t.strftime("%m"), t.strftime("%d"), t.strftime("%H"), t.strftime("%M"), t.strftime("%S"), ) if online: resp = r.load_account_profile() if log: if not os.path.exists(account_profile_output_dir): os.makedirs(account_profile_output_dir) account_profile_output_file = os.path.join( account_profile_output_dir, "{}.json".format(t.strftime("%Y_%m_%d_%H_%M_%S")), ) with open(account_profile_output_file, "w") as f: f.write(json.dumps(resp, indent=4)) else: latest = datetime.strptime( latest_ds(account_profile_base_dir), "%Y/%m/%d/%H/%M/%S" ) account_profile_latest_file: str = os.path.join( account_profile_base_dir, latest.strftime("%Y"), latest.strftime("%m"), latest.strftime("%d"), latest.strftime("%H"), latest.strftime("%M"), latest.strftime("%S"), "{}.json".format(latest.strftime("%Y_%m_%d_%H_%M_%S")), ) resp = json.load(open(account_profile_latest_file, "r")) assert "margin_balances" in resp assert "unallocated_margin_cash" in resp["margin_balances"] buying_power: float = float( resp["margin_balances"]["unallocated_margin_cash"] ) return AccountProfile(buying_power)
def test_load_account_profile(self): profile = r.load_account_profile(info=None) assert profile assert ('url' in profile) assert ('portfolio_cash' in profile) assert ('can_downgrade_to_cash' in profile) assert ('user' in profile) assert ('account_number' in profile) assert ('type' in profile) assert ('created_at' in profile) assert ('updated_at' in profile) assert ('deactivated' in profile) assert ('deposit_halted' in profile) assert ('only_position_closing_trades' in profile) assert ('buying_power' in profile) assert ('cash_available_for_withdrawal' in profile) assert ('cash' in profile) assert ('cash_held_for_orders' in profile) assert ('uncleared_deposits' in profile) assert ('sma' in profile) assert ('sma_held_for_orders' in profile) assert ('unsettled_funds' in profile) assert ('unsettled_debit' in profile) assert ('crypto_buying_power' in profile) assert ('max_ach_early_access_amount' in profile) assert ('cash_balances' in profile) assert ('margin_balances' in profile) assert ('sweep_enabled' in profile) assert ('instant_eligibility' in profile) assert ('option_level' in profile) assert ('is_pinnacle_account' in profile) assert ('rhs_account_number' in profile) assert ('state' in profile) assert ('active_subscription_id' in profile) assert ('locked' in profile) assert ('permanently_deactivated' in profile) assert ('received_ach_debit_locked' in profile) assert ('drip_enabled' in profile) assert ('eligible_for_fractionals' in profile) assert ('eligible_for_drip' in profile) assert ('eligible_for_cash_management' in profile) assert ('eligible_for_trading_on_expiration' in profile) assert ('cash_management_enabled' in profile) assert ('option_trading_on_expiration_enabled' in profile) assert ('cash_held_for_options_collateral' in profile) assert ('fractional_position_closing_only' in profile) assert ('user_id' in profile) assert ('rhs_stock_loan_consent_status' in profile)
def amount_to_buy(self): """ Current Rules: 1. Never buy more than 10% of total accound value 2. If there isn't 10% of total available, spend roughly what is left. 3. If less than a dollar is left of buying power, return 0 """ buying_power = float(chirp.load_account_profile()['portfolio_cash']) if buying_power<1: return 0 total_equity = float(chirp.load_portfolio_profile()['equity']) ten_percent_of_portfolio = (buying_power+total_equity)*.1 if ten_percent_of_portfolio<buying_power: return ten_percent_of_portfolio else: return buying_power*.9
def __init__(self, asset_classes, cash_allocation, test=False): self.test = test click.echo('Getting portfolio...') self.holdings = [] holdings = rs.build_holdings() for name, setting in asset_classes.items(): self.holdings.append(AssetClass(name, setting, holdings)) self.total_equity = sum([ac.equity for ac in self.holdings]) self.total_alloc = sum([ac.target_allocation for ac in self.holdings]) self.normalize_allocations() self.cash = max( 0, float(rs.load_account_profile()['buying_power']) - 0.01 - cash_allocation) if test: self.cash += 200
def get_new_stocks(): play_money = float(r.load_account_profile()['margin_balances'].get('day_trade_buying_power')) current_holdings = r.build_holdings().keys() for g in g_sorted[:1]: if g.Symbol in current_holdings: pass else: shares_to_buy = round(play_money/g.last_trade_price) if shares_to_buy > 0: r.orders.order_buy_limit(g.Symbol, int(shares_to_buy), round(float(g.last_trade_price*.995), 2), timeInForce='gfd') play_money = play_money - (shares_to_buy * g.last_trade_price) print('placed for today ', g.Name) for g in tomorrow[:1]: if g.Symbol in current_holdings: pass else: shares_to_buy = round(play_money / g.last_trade_price) if shares_to_buy > 0: r.orders.order_buy_limit(g.Symbol, int(shares_to_buy), round(float(g.last_trade_price * .985), 2), timeInForce='gfd') play_money = play_money - (shares_to_buy * g.last_trade_price) print('placed for tomorrow ', g.Name) for g in g_sorted[1:2]: if g.Symbol in current_holdings: pass else: shares_to_buy = round(play_money/g.last_trade_price) if shares_to_buy > 0: r.orders.order_buy_limit(g.Symbol, int(shares_to_buy), round(float(g.last_trade_price * .995), 2), timeInForce='gfd') print('Runner up today ', g.Name) for g in tomorrow[1:2]: if g.Symbol in current_holdings: pass else: shares_to_buy = round(play_money/g.last_trade_price) if shares_to_buy > 0: r.orders.order_buy_limit(g.Symbol, int(shares_to_buy), round(float(g.last_trade_price * .98), 2), timeInForce='gfd') print('Runner up tomorrow ', g.Name)
def test_load_account_profile(self): profile = r.load_account_profile(info=None) assert profile
def test_login_failed(self): r.logout() profile = r.load_account_profile(info=None) assert profile
def test_key_failed(self): profile = r.load_account_profile(info='cheese') assert profile
def getBuyingPower(): return (float(r.load_account_profile('buying_power')))
# import cashmanagement as cm # import alpacaAPI as aL from config import email, password import datetime as dt import time import robin_stocks as r r.login(email, password) current_time = dt.datetime.now().time() current_min = dt.datetime.now().time().minute trigger = False profit = [] BTC_code_id = 0 filename = str(dt.datetime.now().date()) + '_log.txt' f = open(filename, 'a+') available = r.load_account_profile('crypto_buying_power') f.write( str(dt.datetime.now().time()) + ', Opening available cash ' + available + '\r\n') x = 0 crypto = r.get_crypto_positions('currency') for item in crypto: if item["code"] == 'BTC': BTC_code_id = x x += 1 buy = 0 crypto = r.get_crypto_positions( 'cost_bases') # gets all the crypto positions in a big list/dict print(crypto[4][0]['direct_quantity']) if crypto[4][0]['direct_quantity'] == '0.000000000000000000':
def position_sizing(): account = rs.load_account_profile() cash_balance=account['buying_power'] position_size=round(float(cash_balance)/no_of_stocks_to_trade) return position_size
def get_buying_power(self): return r.load_account_profile()["buying_power"]
bar1low = 0, bar1high = 0, bar1open = 0, bar1time = 0, bar2close = 0, bar2low = 0, bar2high = 0, bar2open = 0, bar2time = 0, local_max = 0 trigger = False BTC_code_id = 0 filename = str(dt.datetime.now().date()) + '_log_three_bar.txt' f = open(filename, 'a+') available = r.load_account_profile('crypto_buying_power') f.write(str(dt.datetime.now().time()) + ', Opening available cash ' + available + '\r\n') x = 0 crypto = r.get_crypto_positions('currency') for item in crypto: if item["code"] == 'BTC': BTC_code_id = x x += 1 crypto = r.get_crypto_positions('cost_bases') # gets all the crypto positions in a big list/dict print(crypto[4][0]['direct_quantity']) if crypto[4][0]['direct_quantity'] == '0.000000000000000000': in_position = False position = 0 stop = 0 take = 0
uName = uPass = def loggingIn(userName, passWord): robin_stocks.login(username=userName, password=passWord) # for login info # inputName = input('Username(email): ') # inputPass = input('Password: '******'' while kill != 'kill': kill = input('Stock ticker: ') output = robin_stocks.get_historicals(kill, bounds='regular') dataFrame = pd.DataFrame(output) print(dataFrame) print(dataFrame.columns) volume = dataFrame['volume'] plt.hist(volume, bins=30) plt.show()
def test_account_profile(self): profile = r.load_account_profile(info=None) self.assertEqual(profile['user'], self.user) self.assertEqual(profile['account_number'], self.account)