Coder Social home page Coder Social logo

sshh12 / tradinhood Goto Github PK

View Code? Open in Web Editor NEW
22.0 4.0 9.0 126 KB

Programmatically trading stocks, crypto, and options with Robinhood.

License: MIT License

Python 100.00%
robinhood robinhood-api stocks cryptocurrency crypto-trading robinhood-python robinhood-crypto

tradinhood's Introduction

Tradinhood

Programmatically trading stocks and crypto with Robinhood.

$ pip install git+https://github.com/sshh12/Tradinhood.git --upgrade

Docs

Robinhood

Example Usage:

from tradinhood import Robinhood
from decimal import Decimal
import random

rbh = Robinhood()

rbh.login(username="l33tTrader", password="pa5s0rd")
rbh.save_login()
# or
rbh.login(token="sPP80a1qYJPdiUdq.fqhQq4yLaH8QIxKqG8eni759DfdZOi2BTZcnbnCB...")
rbh.save_login()
# or
rbh.load_login()

# Use rbh[...] to retrieve stocks and currencies
dogecoin = rbh['DOGE']
apple = rbh['AAPL']

# num shares owned in apple
apple_shares = rbh.quantity(apple)

# See more info about AAPL
print(apple.popularity)
print(apple.ratings)
print(apple.earnings)
print(apple.fundamentals)
print(apple.get_similar())
print(apple.get_news())

# Check options
for option in apple.puts:
    print(option.iv)
    print(option.greeks)

# (WARN: Do NOT run this code)
do_not_run_me() # just in case

random_option = random.choice(apple.puts)
rbh.order_options([('buy', random_option, 'open')], quantity=1, price=4.20)

# Time to switch to Dogecoin...ditch Apple stock
rbh.sell(apple, apple_shares, type='market')

# A couple mins later...
money_gained = apple_shares * apple.price
print('Sold abt $', money_gained, 'of AAPL')

rbh.buy(dogecoin, money_gained / dogecoin.price, type='limit', price=Decimal('0.0001'))

# Need more doge
rbh.buy(dogecoin, rbh.buying_power / dogecoin.price, type='market')

# Savor your abundant wealth
print(rbh.quantity('DOGE', include_held=True))
# or
print(rbh.get_assets()) # see everything you own as a dict(asset:amt)

# jkjk cancel everything
for order in rbh.orders:
    if order.state == 'confirmed' and order.asset_type == 'cryptocurrency':
        order.cancel()
        rbh.wait_for_orders([order]) # wait for cancel

# also
_, movers = rbh.get_stocks_by_tag('top-movers')
print(rbh.get_bulk_popularity(movers))

# See how you've gained/lost money over time
print(rbh.history())
from tradinhood.tools import order_profit_loss

print(order_profit_loss(rbh, pages=3, include_options=False))

Relevant

Unoffical API Docs sanko/Robinhood

Another Robinhood API Jamonek/Robinhood

tradinhood's People

Contributors

sshh12 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

tradinhood's Issues

OHCLV data straight outta Robinhood

Hey Shrivu. It is cool that your library provides an interface to OHCLV data from google and cryptocompare, but I would also like to be able to get it straight from Robinhood. I know it doesn't go back very far, but still - it's good to have access to price data straight from the exchange you're trading on. If you would be interested in implementing this, you could reference how wang-ye does it in robinhood-crypto.

Any simple way to get price or symbol while iterating positions?

Maybe I'm missing this feature, but I can't see either of those attributes on positions in the API.
My workaround for now is:

for position in rbh.positions:
  print(rbh[rbh.session.get(position['instrument']).json()['symbol']].price)

If the API supports a simpler approach, please document it.
Otherwise, please consider adding this functionality.

Tradinhood rules. Thank you.

400 error at login

I'm new to this repo and am unable to get passed the login.

$ python3
Python 3.7.4 (default, Jul 11 2019, 10:43:21)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

import config
from tradinhood import Robinhood
rbh = Robinhood()
rbh.login(username=config.robinhood_username, password=config.robinhood_password)
Traceback (most recent call last):
File "/tmp/rh/lib/python3.7/site-packages/tradinhood/robinhood.py", line 167, in login
res.raise_for_status()
File "/tmp/rh/lib/python3.7/site-packages/requests/models.py", line 940, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://api.robinhood.com/oauth2/token/

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "", line 1, in
File "/tmp/rh/lib/python3.7/site-packages/tradinhood/robinhood.py", line 170, in login
raise APIError('Login failed')
tradinhood.robinhood.APIError: Login failed

urllib3 errors

Today I have gotten two different errors from urllib3 through Tradinhood.
The first is "Connection aborted, Remote end closed connection without response" while querying account_info on line 452 of Robinhood.py.
The second is "Connection aborted, OSError(22, 'Invalid argument'))" when querying current_quote from line 566 of Robinhood.py.
In both cases I would expect Tradinhood to gracefully handle the errors without unexpectedly terminating.
Please let me know if you would like me to open a second issue to separate the two errors, or in case there is any further information I can provide. Thank you.

I believe I was running on commit 708c68b when I got the following error:

Traceback (most recent call last):
  File "/usr/lib/python3.7/site-packages/urllib3/connectionpool.py", line 600, in urlopen
    chunked=chunked)
  File "/usr/lib/python3.7/site-packages/urllib3/connectionpool.py", line 384, in _make_request
    six.raise_from(e, None)
  File "<string>", line 2, in raise_from
  File "/usr/lib/python3.7/site-packages/urllib3/connectionpool.py", line 380, in _make_request
    httplib_response = conn.getresponse()
  File "/usr/lib/python3.7/http/client.py", line 1321, in getresponse
    response.begin()
  File "/usr/lib/python3.7/http/client.py", line 296, in begin
    version, status, reason = self._read_status()
  File "/usr/lib/python3.7/http/client.py", line 265, in _read_status
    raise RemoteDisconnected("Remote end closed connection without"
http.client.RemoteDisconnected: Remote end closed connection without response

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3.7/site-packages/requests/adapters.py", line 445, in send
    timeout=timeout
  File "/usr/lib/python3.7/site-packages/urllib3/connectionpool.py", line 638, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "/usr/lib/python3.7/site-packages/urllib3/util/retry.py", line 367, in increment
    raise six.reraise(type(error), error, _stacktrace)
  File "/usr/lib/python3.7/site-packages/urllib3/packages/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/usr/lib/python3.7/site-packages/urllib3/connectionpool.py", line 600, in urlopen
    chunked=chunked)
  File "/usr/lib/python3.7/site-packages/urllib3/connectionpool.py", line 384, in _make_request
    six.raise_from(e, None)
  File "<string>", line 2, in raise_from
  File "/usr/lib/python3.7/site-packages/urllib3/connectionpool.py", line 380, in _make_request
    httplib_response = conn.getresponse()
  File "/usr/lib/python3.7/http/client.py", line 1321, in getresponse
    response.begin()
  File "/usr/lib/python3.7/http/client.py", line 296, in begin
    version, status, reason = self._read_status()
  File "/usr/lib/python3.7/http/client.py", line 265, in _read_status
    raise RemoteDisconnected("Remote end closed connection without"
urllib3.exceptions.ProtocolError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "~/Tradinhood/Tradinhood/Robinhood.py", line 448, in account_info
    res = self.session.get(ENDPOINTS['accounts'] + self.acc_num)
  File "/usr/lib/python3.7/site-packages/requests/sessions.py", line 525, in get
    return self.request('GET', url, **kwargs)
  File "/usr/lib/python3.7/site-packages/requests/sessions.py", line 512, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/lib/python3.7/site-packages/requests/sessions.py", line 622, in send
    r = adapter.send(request, **kwargs)
  File "/usr/lib/python3.7/site-packages/requests/adapters.py", line 495, in send
    raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "./tradinhood.py", line 235, in <module>
    wealth_now = wealth()
  File "./tradinhood.py", line 114, in wealth
    return buy_power() + stock_value() + crypto_value(data) + dollars_pending()
  File "./tradinhood.py", line 117, in buy_power
    return Decimal(rbh.account_info['margin_balances']['overnight_buying_power'])
  File "~/Tradinhood/Tradinhood/Robinhood.py", line 452, in account_info
    raise APIError('Unable to access account')
Tradinhood.Robinhood.APIError: Unable to access account

After that I pulled the latest (0698a93) and got the following error:

Traceback (most recent call last):
  File "/usr/lib/python3.7/site-packages/urllib3/connectionpool.py", line 600, in urlopen
    chunked=chunked)
  File "/usr/lib/python3.7/site-packages/urllib3/connectionpool.py", line 384, in _make_request
    six.raise_from(e, None)
  File "<string>", line 2, in raise_from
  File "/usr/lib/python3.7/site-packages/urllib3/connectionpool.py", line 380, in _make_request
    httplib_response = conn.getresponse()
  File "/usr/lib/python3.7/http/client.py", line 1321, in getresponse
    response.begin()
  File "/usr/lib/python3.7/http/client.py", line 296, in begin
    version, status, reason = self._read_status()
  File "/usr/lib/python3.7/http/client.py", line 257, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "/usr/lib/python3.7/socket.py", line 589, in readinto
    return self._sock.recv_into(b)
  File "/usr/lib/python3.7/ssl.py", line 1049, in recv_into
    return self.read(nbytes, buffer)
  File "/usr/lib/python3.7/ssl.py", line 908, in read
    return self._sslobj.read(len, buffer)
OSError: [Errno 22] Invalid argument

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3.7/site-packages/requests/adapters.py", line 445, in send
    timeout=timeout
  File "/usr/lib/python3.7/site-packages/urllib3/connectionpool.py", line 638, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "/usr/lib/python3.7/site-packages/urllib3/util/retry.py", line 367, in increment
    raise six.reraise(type(error), error, _stacktrace)
  File "/usr/lib/python3.7/site-packages/urllib3/packages/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/usr/lib/python3.7/site-packages/urllib3/connectionpool.py", line 600, in urlopen
    chunked=chunked)
  File "/usr/lib/python3.7/site-packages/urllib3/connectionpool.py", line 384, in _make_request
    six.raise_from(e, None)
  File "<string>", line 2, in raise_from
  File "/usr/lib/python3.7/site-packages/urllib3/connectionpool.py", line 380, in _make_request
    httplib_response = conn.getresponse()
  File "/usr/lib/python3.7/http/client.py", line 1321, in getresponse
    response.begin()
  File "/usr/lib/python3.7/http/client.py", line 296, in begin
    version, status, reason = self._read_status()
  File "/usr/lib/python3.7/http/client.py", line 257, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "/usr/lib/python3.7/socket.py", line 589, in readinto
    return self._sock.recv_into(b)
  File "/usr/lib/python3.7/ssl.py", line 1049, in recv_into
    return self.read(nbytes, buffer)
  File "/usr/lib/python3.7/ssl.py", line 908, in read
    return self._sslobj.read(len, buffer)
urllib3.exceptions.ProtocolError: ('Connection aborted.', OSError(22, 'Invalid argument'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "~/Tradinhood/Tradinhood/Robinhood.py", line 562, in current_quote
    res = self.session.get(ENDPOINTS['forex_market_quote'] + self.pair_id + '/')
  File "/usr/lib/python3.7/site-packages/requests/sessions.py", line 525, in get
    return self.request('GET', url, **kwargs)
  File "/usr/lib/python3.7/site-packages/requests/sessions.py", line 512, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/lib/python3.7/site-packages/requests/sessions.py", line 622, in send
    r = adapter.send(request, **kwargs)
  File "/usr/lib/python3.7/site-packages/requests/adapters.py", line 495, in send
    raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', OSError(22, 'Invalid argument'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "./tradinhood.py", line 212, in <module>
    symbol_stats['price'] = rbh[symbol].price.normalize()
  File "~/Tradinhood/Tradinhood/Robinhood.py", line 571, in price
    return Decimal(self.current_quote['mark_price'])
  File "~/Tradinhood/Tradinhood/Robinhood.py", line 566, in current_quote
    raise APIError('Unable to access currency data')
Tradinhood.Robinhood.APIError: Unable to access currency data

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.