Skip to content

Commit

Permalink
Merge pull request #471 from henryzhangpku/master
Browse files Browse the repository at this point in the history
enable multi-acounts monitoring & 24 hours ordering
  • Loading branch information
jmfernandes authored May 11, 2024
2 parents 6dc9dac + 54e95a9 commit 2ba3148
Show file tree
Hide file tree
Showing 6 changed files with 40 additions and 24 deletions.
9 changes: 4 additions & 5 deletions robin_stocks/robinhood/account.py
Original file line number Diff line number Diff line change
Expand Up @@ -811,24 +811,23 @@ def build_holdings(with_dividends=False):


@login_required
def build_user_profile():
def build_user_profile(account_number=None):
"""Builds a dictionary of important information regarding the user account.
:returns: Returns a dictionary that has total equity, extended hours equity, cash, and divendend total.
"""
user = {}

portfolios_data = load_portfolio_profile()
accounts_data = load_account_profile()
portfolios_data = load_portfolio_profile(account_number=account_number)
accounts_data = load_account_profile(account_number=account_number)

if portfolios_data:
user['equity'] = portfolios_data['equity']
user['extended_hours_equity'] = portfolios_data['extended_hours_equity']

if accounts_data:
cash = "{0:.2f}".format(
float(accounts_data['cash']) + float(accounts_data['uncleared_deposits']))
cash = "{0:.2f}".format(float(accounts_data['portfolio_cash'])) # float(accounts_data['cash']) + uncleared_deposits
user['cash'] = cash

user['dividend_total'] = get_total_dividends()
Expand Down
2 changes: 1 addition & 1 deletion robin_stocks/robinhood/globals.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"Accept-Encoding": "gzip,deflate,br",
"Accept-Language": "en-US,en;q=1",
"Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
"X-Robinhood-API-Version": "1.315.0",
"X-Robinhood-API-Version": "1.431.4",
"Connection": "keep-alive",
"User-Agent": "*"
}
Expand Down
12 changes: 6 additions & 6 deletions robin_stocks/robinhood/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def write_spinner():
sys.stdout.write('\b'*(len(marketString)+1))

@login_required
def get_aggregate_positions(info=None):
def get_aggregate_positions(info=None, account_number=None):
"""Collapses all option orders for a stock into a single dictionary.
:param info: Will filter the results to get a specific value.
Expand All @@ -30,12 +30,12 @@ def get_aggregate_positions(info=None):
a list of strings is returned where the strings are the value of the key that matches info.
"""
url = aggregate_url()
url = aggregate_url(account_number=account_number)
data = request_get(url, 'pagination')
return(filter_data(data, info))

@login_required
def get_aggregate_open_positions(info=None):
def get_aggregate_open_positions(info=None, account_number=None):
"""Collapses all open option positions for a stock into a single dictionary.
:param info: Will filter the results to get a specific value.
Expand All @@ -44,7 +44,7 @@ def get_aggregate_open_positions(info=None):
a list of strings is returned where the strings are the value of the key that matches info.
"""
url = aggregate_url()
url = aggregate_url(account_number=account_number)
payload = {'nonzero': 'True'}
data = request_get(url, 'pagination', payload)
return(filter_data(data, info))
Expand All @@ -67,7 +67,7 @@ def get_market_options(info=None):


@login_required
def get_all_option_positions(info=None):
def get_all_option_positions(info=None, account_number=None):
"""Returns all option positions ever held for the account.
:param info: Will filter the results to get a specific value.
Expand All @@ -76,7 +76,7 @@ def get_all_option_positions(info=None):
a list of strings is returned where the strings are the value of the key that matches info.
"""
url = option_positions_url()
url = option_positions_url(account_number=account_number)
data = request_get(url, 'pagination')
return(filter_data(data, info))

Expand Down
18 changes: 13 additions & 5 deletions robin_stocks/robinhood/orders.py
Original file line number Diff line number Diff line change
Expand Up @@ -833,11 +833,16 @@ def order(symbol, quantity, side, limitPrice=None, stopPrice=None, account_numbe
trigger = "stop"
else:
price = round_price(next(iter(get_latest_price(symbol, priceType, extendedHours)), 0.00))

from datetime import datetime
payload = {
'account': load_account_profile(account_number=account_number, info='url'),
'instrument': get_instruments_by_symbols(symbol, info='url')[0],
'symbol': symbol,
'price': price,
'ask_price': round_price(next(iter(get_latest_price(symbol, "ask_price", extendedHours)), 0.00)),
'bid_ask_timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'),
'bid_price': round_price(next(iter(get_latest_price(symbol, "bid_price", extendedHours)), 0.00)),
'quantity': quantity,
'ref_id': str(uuid4()),
'type': orderType,
Expand All @@ -852,7 +857,8 @@ def order(symbol, quantity, side, limitPrice=None, stopPrice=None, account_numbe
# adjust market orders
if orderType == 'market':
del payload['stop_price']
del payload['extended_hours']
# if market_hours == 'regular_hours':
# del payload['extended_hours']

if market_hours == 'regular_hours':
if side == "buy":
Expand All @@ -862,11 +868,12 @@ def order(symbol, quantity, side, limitPrice=None, stopPrice=None, account_numbe
elif orderType == 'market' and side == 'sell':
del payload['price']
elif market_hours == 'all_day_hours':

payload['type'] = 'limit'
payload['quantity']=int(payload['quantity']) # round to integer instead of fractional

url = orders_url()

# print(payload)
data = request_post(url, payload, jsonify_data=jsonify)

return(data)
Expand Down Expand Up @@ -901,7 +908,7 @@ def order_option_credit_spread(price, symbol, quantity, spread, timeInForce='gtc
such as the order id, the state of order (queued, confired, filled, failed, canceled, etc.), \
the price, and the quantity.
"""
return(order_option_spread("credit", price, symbol, quantity, spread, account_number, timeInForce, jsonify))
return(order_option_spread("credit", price, symbol, quantity, spread, timeInForce, account_number, jsonify))


@login_required
Expand Down Expand Up @@ -933,7 +940,7 @@ def order_option_debit_spread(price, symbol, quantity, spread, timeInForce='gtc'
such as the order id, the state of order (queued, confired, filled, failed, canceled, etc.), \
the price, and the quantity.
"""
return(order_option_spread("debit", price, symbol, quantity, spread, account_number, timeInForce, jsonify))
return(order_option_spread("debit", price, symbol, quantity, spread, timeInForce, account_number, jsonify))


@login_required
Expand Down Expand Up @@ -980,7 +987,7 @@ def order_option_spread(direction, price, symbol, quantity, spread, account_numb
each['optionType'])
legs.append({'position_effect': each['effect'],
'side': each['action'],
'ratio_quantity': 1,
'ratio_quantity': each['ratio_quantity'],
'option': option_instruments_url(optionID)})

payload = {
Expand Down Expand Up @@ -1061,6 +1068,7 @@ def order_buy_option_limit(positionEffect, creditOrDebit, price, symbol, quantit
}

url = option_orders_url()
# print(payload)
data = request_post(url, payload, json=True, jsonify_data=jsonify)

return(data)
Expand Down
9 changes: 6 additions & 3 deletions robin_stocks/robinhood/profiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ def load_investment_profile(info=None):


@login_required
def load_portfolio_profile(info=None):
def load_portfolio_profile(account_number=None, info=None):
"""Gets the information associated with the portfolios profile,
such as withdrawable amount, market value of account, and excess margin.
Expand Down Expand Up @@ -169,8 +169,11 @@ def load_portfolio_profile(info=None):
* unwithdrawable_grants
"""
url = portfolio_profile_url()
data = request_get(url, 'indexzero')
url = portfolio_profile_url(account_number)
if account_number is not None:
data = request_get(url)
else:
data = request_get(url, 'indexzero')
return(filter_data(data, info))


Expand Down
14 changes: 10 additions & 4 deletions robin_stocks/robinhood/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,11 @@ def investment_profile_url():
return('https://api.robinhood.com/user/investment_profile/')


def portfolio_profile_url():
return('https://api.robinhood.com/portfolios/')
def portfolio_profile_url(account_number=None):
if account_number:
return('https://api.robinhood.com/portfolios/'+account_number)
else:
return('https://api.robinhood.com/portfolios/')


def security_profile_url():
Expand Down Expand Up @@ -192,8 +195,11 @@ def market_category_url(category):
# options


def aggregate_url():
return('https://api.robinhood.com/options/aggregate_positions/')
def aggregate_url(account_number):
if account_number:
return('https://api.robinhood.com/options/aggregate_positions/?account_numbers='+account_number)
else:
return('https://api.robinhood.com/options/aggregate_positions/')


def chains_url(symbol):
Expand Down

0 comments on commit 2ba3148

Please sign in to comment.