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 getAllCryptoPositions(): positions = r.get_crypto_positions() cryptopositions = [] for x in range(0, len(positions)): details = positions[x] costbasislist = details['cost_bases'] costbasis = costbasislist[0] currency = details['currency'] cryptoposition = [] cryptoposition.append(currency['code']) cryptoposition.append(details['quantity_available']) cryptoposition.append(details['quantity_held_for_sell']) cryptoposition.append(details['quantity_held_for_buy']) if float(details['quantity_available']) > 0 or float( details['quantity_held_for_sell']) > 0: preavgprice = Decimal(float( costbasis['direct_cost_basis'])) / Decimal( float(costbasis['direct_quantity'])) avgprice = round(float(preavgprice), 6) cryptoposition.append(str(avgprice)) else: cryptoposition.append(str(0.00)) cryptopositions.append(cryptoposition) return (cryptopositions)
def check_cash_on_hand(self, symbol="USD"): cash_on_hand = 0 if symbol == "USD": info = rh.load_phoenix_account() if info is None: raise ConnectionError cash_on_hand = float(info['account_buying_power']['amount']) # TODO: # If we want to separate this bot from the rest of the acct, then we will need to # do other calculations here based on orders placed and total amount willing to invest. # If we're fine using the entire account balance for this bot, then we only need # to return the account_buying_power. else: crypto_on_hand = dict() crypto_positions = rh.get_crypto_positions() if crypto_positions is None: raise ConnectionError if symbol not in self.ndigits.keys(): self.ndigits[symbol] = float_to_ndigits( float( list( filter(lambda x: x['currency']['code'] == symbol, crypto_positions))[0]['currency'] ['increment'])) self.ndigits[symbol] = min(8, self.ndigits[symbol]) try: crypto_on_hand['cost'] = float( list( filter(lambda x: x['currency']['code'] == symbol, crypto_positions))[0]['cost_bases'][0] ['direct_cost_basis']) except IndexError: crypto_on_hand['cost'] = 0 try: crypto_on_hand['quantity'] = float( list( filter(lambda x: x['currency']['code'] == symbol, crypto_positions))[0]['quantity']) except IndexError: crypto_on_hand['quantity'] = 0 get_quote = rh.get_crypto_quote(symbol) crypto_on_hand['bid_price'] = float(get_quote['bid_price']) crypto_on_hand['ask_price'] = float(get_quote['ask_price']) crypto_on_hand['quote'] = float(get_quote['bid_price']) crypto_on_hand[ 'value'] = crypto_on_hand['quote'] * crypto_on_hand['quantity'] cash_on_hand = crypto_on_hand return cash_on_hand
def test_crypto_positions(self): positions = r.get_crypto_positions(info=None) first = positions[0] assert (first['account_id'] == self.account) assert ('account_id' in first) assert ('cost_bases' in first) assert ('created_at' in first) assert ('currency' in first) assert ('id' in first) assert ('quantity' in first) assert ('quantity_available' in first) assert ('quantity_held_for_buy' in first) assert ('quantity_held_for_sell' in first) assert ('updated_at' in first)
def test_crypto_positions(self): positions = r.get_crypto_positions(info=None) first = positions[0] self.assertEqual(first['account_id'], self.account) self.assertIn('account_id', first) self.assertIn('cost_bases', first) self.assertIn('created_at', first) self.assertIn('currency', first) self.assertIn('id', first) self.assertIn('quantity', first) self.assertIn('quantity_available', first) self.assertIn('quantity_held_for_buy', first) self.assertIn('quantity_held_for_sell', first) self.assertIn('updated_at', first)
def getHoldings(self, ticker): # this contains the amount we currently own by id and code # quantity_available may be better quantity = 0.0 try: result = r.get_crypto_positions() for t in range(0, len(result)): symbol = result[t]['currency']['code'] if (symbol == ticker): quantity = result[t]['quantity'] except: print("Got exception while getting holdings from RobinHood.") quantity = -1.0 return float(quantity)
def get_my_cypto_value(): data = r.get_crypto_positions() #print(data) qt = float(data[0]['quantity']) return round(qt * f.get_cypto_price(), 2)
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': in_position = False position = 0 stop = 0 take = 0 else:
def get_total_gains(password): """get_total_gains - Return the total gains for the user's account""" with open(ACCOUNT_JSON, 'r') as f: account = json.load(f) if checkpw(password, account['password']): click.echo("Logged in as " + account['email']) r.login(account['email'], password) profile_data = r.load_portfolio_profile() crypto_positions = r.get_crypto_positions() all_transactions = r.get_bank_transfers() card_transactions = r.get_card_transactions() dividends = r.get_total_dividends() deposits = sum( float(x['amount']) for x in all_transactions if (x['direction'] == 'deposit') and (x['state'] == 'completed')) withdrawals = sum( float(x['amount']) for x in all_transactions if (x['direction'] == 'withdraw') and (x['state'] == 'completed')) debits = sum( float(x['amount']['amount']) for x in card_transactions if (x['direction'] == 'debit' and ( x['transaction_type'] == 'settled'))) reversal_fees = sum( float(x['fees']) for x in all_transactions if (x['direction'] == 'deposit') and (x['state'] == 'reversed')) money_invested = deposits + reversal_fees - (withdrawals - debits) percent_dividend = dividends / money_invested * 100 profile_equity = float(profile_data['extended_hours_equity']) crypto_equity = float( crypto_positions[0]['cost_bases'][0]['direct_cost_basis']) equity = profile_equity + crypto_equity total_gain_minus_dividends = equity - dividends - money_invested percent_gain = total_gain_minus_dividends / money_invested * 100 val = "${:.2f}" valp = "%{:.2f}" data = { '|Total Invested|': [val.format(money_invested)], '|Total Equity|': [val.format(equity)], '|Net Worth (Dividends)|': [(val.format(dividends), valp.format(percent_dividend).replace('%-', '-%'))], '|Net Worth (Other Gains)|': [(val.format(total_gain_minus_dividends), valp.format(percent_gain).replace('%-', '-%'))] } df = pd.DataFrame.from_dict(data) click.echo('\n') click.echo(df.to_string(index=False)) click.echo('\n') else: # Login Unsuccessful click.echo("Incorrect Robinhood Password")
def LOAD_OPEN_CRYPTOS(): func = r.get_crypto_positions() return func
print("\nYou need a file called rh_crypto_data.json in the RAT folder.") print("This file stores a dictionary containing your crypto symbols and the last price you traded each at") print('\nJSON data looks like {"SYM1":1.11, "SYM2":50.49} where each "symbol":price pair is comma separated with no comma after the last pair and with all pairs inside curly brackets {...}') ans = input("Press <Enter> when you have created rh_crypto_data.json.json in the RAT folder") print("\nrh_crypto_data.json in the RAT folder looks like...\n") with open(crypto_file) as json_data: d = json.load(json_data) print(json.dumps(d, indent=1)) input("\nYour cryptos and the last trade prices of each on your account?\n\n<enter> if everything looks correct.\n") #how many symbols are being traded numSymbols = len(d) # print(numSymbols) positions = r.get_crypto_positions() numPositions = len(positions) quantities = {} for i in range(0,numPositions): # print(positions[i]) # print(json.dumps(positions[i],indent=1)) quantities[positions[i]["currency"]["code"]]=float(positions[i]["cost_bases"][0]["direct_quantity"]) mockSpend = 0; mockSell = 0; index = 0 check = {} #s is symbol, d is the whole rh_stock_data json dictionary