Created
September 2, 2024 22:34
-
-
Save classicvalues/ca7da2cec4b7b6474a53724826e5de95 to your computer and use it in GitHub Desktop.
Robinhood Trading -ALL ASSETS- API Code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import robin_stocks.robinhood as r | |
| import time | |
| from datetime import datetime, timedelta | |
| # Set up Robinhood API credentials | |
| username = 'your_robinhood_username' | |
| password = 'your_robinhood_password' | |
| # Login to Robinhood | |
| r.login(username, password) | |
| # Define the trading parameters | |
| symbol = 'GOOGL' | |
| investment_amount = 10.0 # Amount to use per transaction | |
| # Define the time for trading | |
| time_after_open = timedelta(minutes=2) | |
| time_before_close = timedelta(minutes=2) | |
| # Helper function to get the current price | |
| def get_current_price(symbol): | |
| quote = r.stocks.get_quotes(symbol) | |
| return (float(quote[0]['ask_price']) + float(quote[0]['bid_price'])) / 2 # Midpoint between bid and ask | |
| # Helper function to get the current account balance | |
| def get_account_balance(): | |
| account_info = r.profiles.load_account_profile() | |
| return float(account_info['portfolio_cash']) | |
| # Helper function to place orders | |
| def place_order(symbol, notional, side): | |
| if side == 'buy': | |
| r.orders.order_buy_fractional_by_price(symbol, notional, timeInForce='gfd') | |
| elif side == 'sell': | |
| r.orders.order_sell_fractional_by_price(symbol, notional, timeInForce='gfd') | |
| # Helper function to close all positions | |
| def close_all_positions(): | |
| holdings = r.account.build_holdings() | |
| for symbol, position in holdings.items(): | |
| quantity = position['quantity'] | |
| place_order(symbol, quantity, 'sell') | |
| print("Closed all positions.") | |
| # Trading logic | |
| def trade(): | |
| initial_price = get_current_price(symbol) | |
| peak_price = initial_price | |
| trough_price = initial_price | |
| while True: | |
| current_time = datetime.now() | |
| # Assuming market opens at 9:30 AM and closes at 4:00 PM | |
| market_open_time = datetime.combine(current_time.date(), datetime.strptime('09:30', '%H:%M').time()) | |
| market_close_time = datetime.combine(current_time.date(), datetime.strptime('16:00', '%H:%M').time()) | |
| # Calculate trade start and stop times | |
| start_trading_time = market_open_time + time_after_open | |
| stop_trading_time = market_close_time - time_before_close | |
| # Check if current time is within trading hours | |
| if start_trading_time <= current_time <= stop_trading_time: | |
| current_price = get_current_price(symbol) | |
| balance = get_account_balance() | |
| # Update the peak and trough prices | |
| if current_price > peak_price: | |
| peak_price = current_price | |
| if current_price < trough_price: | |
| trough_price = current_price | |
| # Buy when there's a gain, using all available balance | |
| if current_price > initial_price and balance >= investment_amount: | |
| place_order(symbol, investment_amount, 'buy') | |
| print(f"Bought ${investment_amount} worth of {symbol} at {current_price} due to price gain.") | |
| wait_for_balance_to_update() | |
| # Sell when there's a loss | |
| holdings = r.account.build_holdings() | |
| if symbol in holdings and current_price < initial_price: | |
| quantity = holdings[symbol]['quantity'] | |
| place_order(symbol, quantity, 'sell') | |
| print(f"Sold all shares of {symbol} at {current_price} due to price loss.") | |
| wait_for_balance_to_update() | |
| # Shorting is not supported by Robinhood, so we'll skip that part | |
| # Close all positions a couple of minutes before market close | |
| if current_time > stop_trading_time: | |
| close_all_positions() | |
| break # Exit the loop after closing positions for the day | |
| time.sleep(1) # Check as frequently as possible | |
| # Helper function to wait until the account balance updates after a sell | |
| def wait_for_balance_to_update(): | |
| while True: | |
| balance = get_account_balance() | |
| if balance >= investment_amount: | |
| break | |
| time.sleep(1) | |
| # Run the trading strategy | |
| trade() | |
| # Log out of Robinhood | |
| r.logout() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment