Skip to content

Commit

Permalink
Merge pull request robinhood-unofficial#93 from Miserlou/master
Browse files Browse the repository at this point in the history
Adds Cancel Order Function
  • Loading branch information
Jamonek authored Apr 24, 2018
2 parents 97da646 + 5a40838 commit 28e5932
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ See this [blog post](https://medium.com/@rohanpai25/reversing-robinhood-free-acc
## Current Features
- Placing buy orders (`Robinhood.place_buy_order`)
- Placing sell order (`Robinhood.place_sell_order`)
- Fetch and cancel orders (`Robinhood.order_history` and `Robinhood.cancel_order`)
- Quote information (`Robinhood.quote_data`)
- User portfolio data (`Robinhood.portfolios`)
- User positions data (`Robinhood.positions`)
Expand Down
42 changes: 42 additions & 0 deletions Robinhood/Robinhood.py
Original file line number Diff line number Diff line change
Expand Up @@ -1355,3 +1355,45 @@ def submit_order(self,
res.raise_for_status()

return res

##############################
# CANCEL ORDER
##############################

def cancel_order(
self,
order_id
):
"""
Cancels specified order and returns the response (results from `orders` command).
If order cannot be cancelled, `None` is returned.
Args:
order_id (str): Order ID that is to be cancelled or order dict returned from
order get.
Returns:
(:obj:`requests.request`): result from `orders` put command
"""
if order_id is str:
try:
order = self.session.get(self.endpoints['orders'] + order_id, timeout=15).json()
except (requests.exceptions.HTTPError) as err_msg:
raise ValueError('Failed to get Order for ID: ' + order_id
+ '\n Error message: '+ repr(err_msg))
else:
raise ValueError('Cancelling orders requires a valid order_id string')

if order.get('cancel') is not None:
try:
res = self.session.post(order['cancel'], timeout=15)
res.raise_for_status()
except (requests.exceptions.HTTPError) as err_msg:
raise ValueError('Failed to cancel order ID: ' + order_id
+ '\n Error message: '+ repr(err_msg))
return None

# Order type cannot be cancelled without a valid cancel link
else:
raise ValueError('Unable to cancel order ID: ' + order_id)

return res
15 changes: 15 additions & 0 deletions tests/test_portfolio.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,3 +167,18 @@ def test_bad_logout():
req = rh_obj.logout()

assert req.status_code != 200

def test_cancel_bad_order_id():
"""cancel a naughty order id"""
bad_id = '1234Dx'
if not LOGIN_OK:
pytest.xfail('cannot test without valid user/passwd')
rh_obj = Robinhood()
rh_obj.login(
username=CONFIG.get('LOGIN', 'username'),
password=CONFIG.get('LOGIN', 'password')
)
with pytest.raises(ValueError):
rh_obj.cancel_order(bad_id)


0 comments on commit 28e5932

Please sign in to comment.