예제 #1
0
def buy_holdings(potential_buys, profile_data, holdings_data):
    """ Places orders to buy holdings of stocks. This method will try to order
        an appropriate amount of shares such that your holdings of the stock will
        roughly match the average for the rest of your portfoilio. If the share
        price is too high considering the rest of your holdings and the amount of
        buying power in your account, it will not order any shares.

    Args:
        potential_buys(list): List of strings, the strings are the symbols of stocks we want to buy
        symbol(str): Symbol of the stock we want to sell
        holdings_data(dict): dict obtained from r.build_holdings() or get_modified_holdings() method
    """
    cash = float(profile_data.get('cash'))
    portfolio_value = float(profile_data.get('equity')) - cash
    ideal_position_size = (safe_division(portfolio_value, len(holdings_data)) +
                           cash / len(potential_buys)) / (2 *
                                                          len(potential_buys))
    prices = r.get_latest_price(potential_buys)
    for i in range(0, len(potential_buys)):
        stock_price = float(prices[i])
        if (ideal_position_size < stock_price < ideal_position_size * 1.5):
            num_shares = int(ideal_position_size * 1.5 / stock_price)
        elif (stock_price < ideal_position_size):
            num_shares = int(ideal_position_size / stock_price)
        else:
            print("####### Tried buying shares of " + potential_buys[i] +
                  ", but not enough buying power to do so#######")
            break
        print("####### Buying " + str(num_shares) + " shares of " +
              potential_buys[i] + " #######")
        r.order_buy_market(potential_buys[i], num_shares)
예제 #2
0
def buy_shares(symbol, amount):
    print(f'\nBuying {amount} share(s) from {symbol}')
    print('------------------------------------')
    try:
        bot_trader.order_buy_market(symbol=symbol, quantity=amount)
    except Exception as holdings_err:
        exception_log(holdings_err)
    print('------------------------------------\n')
예제 #3
0
def buyStock(stock,shareAmount):
    try:
        rStocks.order_buy_market(stock,shareAmount)
        print(str(shareAmount)+' shares of '+str(stock).upper()+' purchased!')
    except Exception as e:
        print('Log in failed...')
        if hasattr(e,'message'):
            print(e.message)
        else:
            print(e)
        pass
예제 #4
0
 def buy_long(self, stock):
     buying_power = float(r.profiles.load_account_profile()
                          ['margin_balances']['day_trade_buying_power'])
     if not self.my_stocks:
         try:
             qty = floor(buying_power /
                         float(r.stocks.get_latest_price(stock)[0]))
             r.order_buy_market(stock, qty)
             print('bought ' + str(qty) + ' : ' + stock)
             self.my_stocks = r.build_holdings()
         except Exception as e:
             print(e)
예제 #5
0
def buy(quantity, symbol, limit):
    if limit is not None:
        ui.success("buying {} of {} at {}".format(quantity, symbol, limit))
        result = rh.order_buy_limit(symbol, quantity, limit)
    else:
        ui.success("buying {} of {}".format(quantity, symbol))
        result = rh.order_buy_market(symbol, quantity)
예제 #6
0
def prompt_user(action, ticker, current_price):
    if action == "BUY":
        answer = None
        while answer not in ("y", "n"):
            answer = input("Proceed with " + action + "? (y/n) ")
            if answer == "y":
                #buy qty of specified stock from Robinhood
                try:
                    robin_stocks.order_buy_market(
                        ticker, share_qty)  #place the buy in Robinhood
                    print("Bought " + str(share_qty) + " share(s) of " +
                          ticker + " on " + str(date.today()) + " at $" +
                          str(current_price))
                    append_to_log(action, "COMPLETED", ticker, current_price)
                except Exception as err:
                    print('Error ' + action.lower() + 'ing ' + ticker + ": " +
                          err)
                    append_to_log(action, "ERROR: " + err, ticker,
                                  current_price)
            elif answer == "n":
                append_to_log(action, "MANUALLY CANCELLED", ticker,
                              current_price)
            else:
                print("Please enter y or n")
    elif action == "SELL":
        answer = None
        while answer not in ("y", "n"):
            answer = input("Proceed with " + action + "? (y/n) ")
            if answer == "y":
                #sell qty of specified stock from Robinhood
                try:
                    robin_stocks.order_sell_market(
                        ticker, share_qty)  #place the sell in Robinhood
                    print("Sold " + str(share_qty) + " share(s) of " + ticker +
                          " on " + str(date.today()) + " at $" +
                          str(current_price))
                    append_to_log(action, "COMPLETED", ticker, current_price)
                except Exception as err:
                    print('Error ' + action.lower() + 'ing ' + ticker + ": " +
                          err)
                    append_to_log(action, "ERROR: " + err, ticker,
                                  current_price)
            elif answer == "n":
                append_to_log(action, "MANUALLY CANCELLED", ticker,
                              current_price)
            else:
                print("Please enter y or n")
예제 #7
0
def buy(quantity, symbol, limit):
    if limit is not None:
        ui.success(f"Bying {quantity} of {symbol} at ${limit}")
        result = rh.order_buy_limit(symbol, quantity, limit)
    else:
        ui.success(f'Bying {quantity} of {symbol} at market price....\n')
        result = rh.order_buy_market(symbol, quantity)

    ui.chec_ref(result)
def buy(quantity, symbol, limit):
    if limit is not None:#limit order 
        click.echo(click.style("Buying {} of {} at ${}".format(quantity,symbol,limit), fg = "green", bold = True))
        result = rh.order_buy_limit(symbol,quantity,limit)
        
    else:#market order
        click.echo(click.style("Buying {} of {} at market value".format(quantity,symbol), fg = "green", bold = True))
        result = rh.order_buy_market(symbol,quantity)
    
    print(result)
def buy(quantity, symbol, limit):
    if limit is not None:
        robinhood_ui.success("buying {} of {} at {}".format(quantity, symbol, limit))
        result = rh.order_buy_limit(symbol, quantity, limit)
    else:
        robinhood_ui.success("buying {} of {} at market price".format(quantity, symbol))
        result = rh.order_buy_market(symbol, quantity)
    if 'ref_id' in result:
        robinhood_ui.success(result)
    else:
        robinhood_ui.error(result)
예제 #10
0
 def marketBuy(self, stock, quantity):
     # submit a purchase order at market price
     try:
         response = robin.order_buy_market(stock, quantity)
         #TODO: look up what response contains and get the exact order price and log it out. same for other methods
     except Exception as ex:
         logger.logError(
             'Unable to purchase %s with market buy. \nError: %s ' %
             (stock, ex))
     else:
         logger.logInfo(
             'Successfully purchased %i shares of %s with market buy' %
             (quantity, stock))
예제 #11
0
파일: robin.py 프로젝트: sgirap/Stocks
def buy(quantity, symbol, limit=None):
    content = open('config.json').read()
    config = json.loads(content)
    rh.login(config['username'], config['password'])

    if limit is not None:
        ui.success("buying {} of {} at ${}".format(quantity, symbol, limit))
        result = rh.order_buy_limit(symbol, quantity, limit)
    else:
        ui.success("buying {} of {}".format(quantity, symbol))
        result = rh.order_buy_market(symbol, quantity)
    if 'detail' in result:
        ui.error(result)
    else:
        ui.success(result)
예제 #12
0
파일: views.py 프로젝트: Rushilwiz/reinvest
    def create(self, request, *args, **kwargs):
        import copy
        data = copy.deepcopy(request.data)
        data.update({'user': request.user})
        serializer = StockCreateSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        login = r.login(os.getenv("ROBINHOOD_USER"),
                        os.getenv("ROBINHOOD_PASS"))
        order = r.order_buy_market(symbol=serializer.data['ticker'],
                                   quantity=serializer.data['quantity'])
        stonks = r.build_holdings()
        for key, value in stonks.items():
            if Stock.objects.filter(uuid=value['id']).count() != 1:
                stock = Stock.objects.create(user=request.user.profile,
                                             quantity=ceil(
                                                 float(value['quantity'])),
                                             ticker=key,
                                             buy_price=value['price'],
                                             uuid=value['id'])

        return Response(serializer.data, status=status.HTTP_200_OK)
예제 #13
0
 def buy_shares_at_market_price(symbol: str, quantity: int) -> None:
     order_buy_market(symbol=symbol, quantity=quantity)
예제 #14
0
 def order_buy_market(self, symbol, quantity):
     buy_status = r.order_buy_market(symbol, quantity)
     self.my_stocks = self.refresh_holdings()
     return buy_status
예제 #15
0
    cross = get_last_crossing(df, days, symbol=stockTicker, direction=direction)

    return cross


r.login('*****@*****.**', 'Holimont3!')

# build_holdings() compiles all stocks into a dict
my_stocks = r.build_holdings()

for key, value in my_stocks.items():
	print(key, value)

print('Would you like to buy a stock? (Y/N)')
answer = input()
if answer.lower() == "y":
	print("Enter Symbol")
	symbol = input()
	symbol = symbol.upper()
	print("Enter Quantity")
	quantity = input()
	if quantity.isdigit():
		print('Buy', quantity, 'shares of', symbol, 'Stock? (Y/N)')
		answer = input()
		if answer.lower() == 'y':
			r.order_buy_market(symbol, quantity)
else:
	example = golden_cross('GOOGL', 50, 200, 10, "Above")
	print(example)

예제 #16
0
파일: rhood.py 프로젝트: bhbmaster/rhood
def SELL_STOCK(symbol, amount_of_shares):
    ans=r.order_buy_market(symbol,amount_of_shares)
    return ans
예제 #17
0
        if(count>1000):
            break

        #####################################################################   SAVE
        if(in_time_range('0800-1730')):

                count = count + 1
                my_stocks = robin_stocks.build_holdings()

                cur = robin_stocks.stocks.get_latest_price('SAVE', True)
                cur = float(cur[0])

                print('Spirit -->  ' + str(datetime.datetime.now()) +  '    Price -->  '  +  str(cur)    + '  ---------------> SAVE' )

                if(cur < 9.0 and SAVE_FLAG == False):
                    robin_stocks.order_buy_market('SAVE', 110)  # buy!
                    SAVE_FLAG = True
                    print('Bought ' + str(110) + ' SAVE !!!')

        #####################################################################   Zoom
                count = count + 1
                my_stocks = robin_stocks.build_holdings()

                cur = robin_stocks.stocks.get_latest_price('ZM', True)
                cur = float(cur[0])

                print('Zoom   -->  ' + str(datetime.datetime.now()) +  '    Price -->  '  +  str(cur)   )

                if(cur < 133 and ZOOM_FLAG == False):
                    robin_stocks.order_buy_market('ZM', 7)  # buy!
                    ZOOM_FLAG = True
예제 #18
0
        file = open('2020_0521_SAVE.csv', 'r')

        print('--20--')
        ## ************************ Get 20 minutes history ************************
        file.close
        file = open('2020_0521_SAVE.csv', 'r')
        his20 = getTail(file, 20)
        his20 = his20[2:]
        his20 = his20[:-1]
        his20 = float(his20)

        rate20_Buy = his20 / cur

        if (rate20_Buy >= 1.02 and already_Buy20 == False):  # buy when DOWN
            hold_price20 = cur  # update hold
            robin_stocks.order_buy_market('SAVE', V)  # buy!
            already_Buy20 = True  # update flag
            print('buy - 20  -->  ' + str(datetime.datetime.now()))
            print('rate20_Buy          ' + str(round(rate20_Buy, 4)))

        rate20_Sell = cur / hold_price20

        if ((rate20_Sell >= 1.01)
                and already_Buy20 == True):  # sell when up 0.1
            print('hold_price20: ' + str(hold_price20))
            robin_stocks.order_sell_market('SAVE', V)
            already_Buy20 = False
            print('sell - 20 -->  ' + str(datetime.datetime.now()))
            print('Earning!!!  -->  ' + str(cur - hold_price20))
            hold_price20 = 77777
            print('rate20_Sell          ' + str(round(rate20_Sell, 4)) +
예제 #19
0
 def buy(self, symbol, quantity):
     quantity = super().buy(symbol, quantity, receipt=True)
     if quantity > 0:
         result = r.order_buy_market(symbol, quantity)
         print(result["state"])
     return quantity
예제 #20
0
def processBuys(buys):
    for symbol, shs in buys.items():
        order = r.order_buy_market(symbol, shs)
예제 #21
0
def main():
    #log start of daily run
    append_to_log("DAILY RUN", "STARTED", "N/A", "N/A")

    #load monitored stock tickers from CSV file
    with open(mt_file, 'r') as ticker_file:
        csv_reader = csv.reader(ticker_file)
        for row in csv_reader:
            monitored_tickers.append(row[0])

    #iterate through each ticker in array and run daily checks
    for ticker in monitored_tickers:
        #set variables
        day_emas = []
        week_emas = []
        keys = []
        vals = []
        intersections = []
        sell_triggers = []
        buy_triggers = []

        #get current stock price
        current_price = si.get_live_price(ticker)
        print("_____________________ " + ticker + " - [" +
              str(round(current_price, 2)) + "]")

        #get actual price
        actual_data, meta_data = ts.get_weekly(symbol=ticker)

        #get day ema
        day_ema, meta_deta = ti.get_ema(symbol=ticker, interval='daily')

        #get weekly ema
        weekly_ema, meta_deta = ti.get_ema(symbol=ticker, interval='weekly')

        for val in day_ema.iterrows():
            day_emas.append([val[0], val[1].values])
        for val in weekly_ema.iterrows():
            week_emas.append([val[0], val[1].values])

        for day in day_emas:
            for week in week_emas:
                if week[0] == day[0]:
                    #print("Date: " + str(day[0]) + " : day ema Price: " + str(day[1][0]) + " : week ema Price: " + str(week[1][0]))
                    keys.append([day[0], day[1][0], week[1][0], ticker])
                    vals.append(day[1][0] - week[1][0])

        for i, v in enumerate(vals):
            if i > 0:
                if v / vals[i - 1] < 0:
                    intersections.append(keys[i])
                    #print("Intersection Happened: " + str(keys[i]))

        #decide if the intersection triggers a buy or sell
        #if the week ema is less than the month ema, sell; if the week ema is more than the month ema, buy
        for intersect in intersections:
            if intersect[1] < intersect[2]:
                sell_triggers.append(intersect)
            elif intersect[1] > intersect[2]:
                buy_triggers.append(intersect)

        print("____________________ v BUY TRIGGERS  v ____________________")
        for buy in buy_triggers:
            print("Buy Trigger: " + str(buy))
        print("____________________ ^ BUY TRIGGERS  ^ ____________________")
        print("____________________ v SELL TRIGGERS v ____________________")
        for sell in sell_triggers:
            print("Sell Trigger: " + str(sell))
        print("____________________ ^ SELL TRIGGERS ^ ____________________")

        try:
            #if the latest buy trigger is today's date, place Robinhood order
            if str(date.today()) == str(
                    buy_triggers[-1][0].to_pydatetime())[:10]:
                print("##### STOCK BUY HAS BEEN TRIGGERED #####")

                action = "BUY"

                append_to_log(action, "STARTED", ticker, current_price)

                #log into Robinhood
                rs_login()

                #plot data with matplotlib
                generate_plot(actual_data, day_ema, weekly_ema, ticker, action)

                #confirm action with user
                #prompt_user(action, ticker, current_price)

                #buy qty of specified stock from Robinhood
                try:
                    robin_stocks.order_buy_market(
                        ticker, share_qty)  #place the buy in Robinhood
                    append_to_log(action, "COMPLETED", ticker, current_price)
                except Exception as err:
                    print('Error ' + action.lower() + 'ing ' + ticker + ": " +
                          err)
                    append_to_log(action, "ERROR: " + err, ticker,
                                  current_price)

            #if the latest sell trigger is today's date, sell shares of that stock
            elif str(date.today()) == str(
                    sell_triggers[-1][0].to_pydatetime())[:10]:
                print("##### STOCK SELL HAS BEEN TRIGGERED #####")

                action = "SELL"

                append_to_log(action, "STARTED", ticker, current_price)

                #log into Robinhood
                rs_login()

                #plot data with matplotlib
                generate_plot(actual_data, day_ema, weekly_ema, ticker, action)

                #confirm action with user
                #prompt_user(action, ticker, current_price)

                #sell qty of specified stock from Robinhood
                try:
                    robin_stocks.order_sell_market(
                        ticker, share_qty)  #place the sell in Robinhood
                    append_to_log(action, "COMPLETED", ticker, current_price)
                except Exception as err:
                    print('Error ' + action.lower() + 'ing ' + ticker + ": " +
                          err)
                    append_to_log(action, "ERROR: " + err, ticker,
                                  current_price)

        except Exception as err:
            print(err)

        #generate_plot(actual_data, day_ema, weekly_ema, ticker, "RUN")
        time.sleep(
            60
        )  #sleep for a minute to wait out the query limit on the free AlphaVantage API

    #log completion of daily run
    append_to_log("DAILY RUN", "COMPLETED", "N/A", "N/A")
    '''
예제 #22
0
NOTE: View the two_factor_log_in.py script to see how automatic
two-factor loggin in works.
'''
### REPLACE ME - order is to buy 1000 shares of BRK.A which should fail for most people
stock = "BRK.A"
quantity = 1000
max_attempts = 10
sleep_time = 1 # in seconds
###
# Load environment variables
load_dotenv()
# Login using two-factor code
totp = pyotp.TOTP(os.environ['robin_mfa']).now()
login = r.login(os.environ['robin_username'], os.environ['robin_password'], store_session=True, mfa_code=totp)
# Here it is important to set jsonify=False so that you can check
# status code of your order request. 200 is ok, 400 is bad request,
# and 404 is unknown url.
order = r.order_buy_market(stock, quantity, jsonify=False)
# Feel free to use more advanced orders
attempts = 0
while order.status_code != 200 and attempts < max_attempts:
    order = r.order_buy_market(stock, quantity, jsonify=False)
    attempts += 1
    sleep(sleep_time)

if attempts == max_attempts:
    print(f"ERROR CODE: {order.status_code}")
    print("max number of tries exceeded. Order failed because ")
    data = order.json()
    print(data['detail'])
예제 #23
0
    async def run(self):
        r.login(os.getenv('ROBINHOOD_USERNAME'),
                os.getenv('ROBINHOOD_PASSWORD'))
        limit_price, stop_price, quantity, amountInDollars = 1.0, 1.0, 1, 1.0
        buy_sell = 'N/A'
        if '$order ' in self.content:
            stock = self.content.replace('$order ', '').upper().split()
            symbol, quantity, buy_sell, limit_price, stop_price, timeout_code = stock
            confirmation = r.order(str(symbol), int(quantity),
                                   (str(buy_sell)).lower(), float(limit_price),
                                   float(stop_price),
                                   (str(timeout_code)).lower())

        elif '$order_buy_market ' in self.content:
            stock = self.content.replace('$order_buy_market ',
                                         '').upper().split()
            symbol, quantity, timeout_code = stock
            confirmation = r.order_buy_market(str(symbol), int(quantity),
                                              str(timeout_code).lower())

        elif '$order_sell_market ' in self.content:
            stock = self.content.replace('$order_sell_market ',
                                         '').upper().split()
            symbol, quantity, buy_sell, limit_price, stop_price, timeout_code = stock
            confirmation = r.order_sell_market(str(symbol), int(quantity),
                                               str(timeout_code).lower())

        elif '$order_buy_limit ' in self.content:
            stock = self.content.replace('$order_buy_limit ',
                                         '').upper().split()
            symbol, quantity, limit_price, timeout_code = stock
            confirmation = r.order_buy_limit(str(symbol), int(quantity),
                                             float(limit_price),
                                             str(timeout_code).lower())

        elif '$order_sell_limit ' in self.content:
            stock = self.content.replace('$order_sell_limit ',
                                         '').upper().split()
            symbol, quantity, limit_price, timeout_code = stock
            confirmation = r.order_sell_limit(str(symbol), int(quantity),
                                              float(limit_price),
                                              str(timeout_code).lower())

        elif '$order_buy_stop_loss ' in self.content:
            stock = self.content.replace('$order_buy_stop_loss ',
                                         '').upper().split()
            symbol, quantity, stop_price, timeout_code = stock
            confirmation = r.order_buy_stop_loss(str(symbol), int(quantity),
                                                 float(stop_price),
                                                 str(timeout_code).lower())

        elif '$order_sell_stop_loss ' in self.content:
            stock = self.content.replace('$order_sell_stop_loss ',
                                         '').upper().split()
            symbol, quantity, stop_price, timeout_code = stock
            confirmation = r.order_sell_stop_loss(str(symbol), int(quantity),
                                                  float(stop_price),
                                                  str(timeout_code).lower())

        elif '$order_buy_trailing_stop ' in self.content:
            stock = self.content.replace('$order_buy_trailing_stop ',
                                         '').upper().split()
            symbol, quantity, trailAmount, trailType, timeout_code = stock
            confirmation = r.order_buy_trailing_stop(str(symbol),
                                                     int(quantity),
                                                     float(trailAmount),
                                                     (str(trailType)).lower(),
                                                     str(timeout_code).lower())

        elif '$order_sell_trailing_stop ' in self.content:
            stock = self.content.replace('$order_sell_trailing_stop ',
                                         '').upper().split()
            symbol, quantity, trailAmount, trailType, timeout_code = stock
            confirmation = r.order_sell_trailing_stop(
                str(symbol), int(quantity), float(trailAmount), str(trailType),
                str(timeout_code).lower())

        elif '$order_sell_stop_limit ' in self.content:
            stock = self.content.replace('$order_sell_stop_limit ',
                                         '').upper().split()
            symbol, quantity, limit_price, stop_price, timeout_code = stock
            confirmation = r.order_sell_stop_limit(str(symbol), int(quantity),
                                                   float(limit_price),
                                                   float(stop_price),
                                                   (str(timeout_code)).lower())

        elif '$order_buy_crypto_limit_by_price ' in self.content:
            stock = self.content.replace('$order_buy_crypto_limit_by_price ',
                                         '').upper().split()
            symbol, amountInDollars, limit_price, timeout_code = stock
            print(str(symbol), float(amountInDollars), float(limit_price),
                  (str(timeout_code)).lower())
            confirmation = r.order_buy_crypto_limit_by_price(
                str(symbol), float(amountInDollars), float(limit_price),
                (str(timeout_code)).lower())

        elif '$order_buy_crypto_by_quantity ' in self.content:
            stock = self.content.replace('$order_buy_crypto_by_quantity ',
                                         '').upper().split()
            symbol, quantity, timeout_code = stock
            confirmation = r.order_buy_crypto_by_quantity(
                str(symbol), int(quantity), (str(timeout_code)).lower())

        elif '$order_sell_crypto_limit_by_price ' in self.content:
            stock = self.content.replace('$order_sell_crypto_limit_by_price ',
                                         '').upper().split()
            symbol, amountInDollars, limit_price, timeout_code = stock
            confirmation = r.order_sell_crypto_limit_by_price(
                str(symbol), float(amountInDollars), float(limit_price),
                (str(timeout_code)).lower())

        elif 'order_sell_crypto_limit ' in self.content:
            stock = self.content.replace('$order_buy_crypto_by_quantity ',
                                         '').upper().split()
            symbol, quantity, limit_price, timeout_code = stock
            confirmation = r.order_sell_crypto_limit(
                str(symbol), int(quantity), float(limit_price),
                (str(timeout_code)).lower())
        print(confirmation)
        message = order_information(symbol, quantity, buy_sell, limit_price,
                                    stop_price, timeout_code)

        if 'id' not in confirmation:
            message = create_simple_message(
                '❌ Order Failed - Details',
                [j for i, j in confirmation.items()])

        self.response.add_response(message)

        if len(self.response.response) == 0:
            self.response.set_error_response(0)
        self.response.done = True
예제 #24
0
def buyStock(ticker, amount):
    try:
        r = rs.order_buy_market(ticker, amount)
        print(r)
    except:
        print('Order did not go through')