Exemple #1
0
 def buy_stock(self, symbol, value):
     value = self.amount_to_buy()
     if value==0:
         self.L.add_line(f'Not enough money to buy {symbol}, purchase not made.')
     else:
         chirp.order_buy_fractional_by_price(symbol, value)
         self.L.add_line('', symbol, 'BOUGHT', value)
         self.my_portfolio.add_to_portfolio(symbol)
Exemple #2
0
def robinbot(buy, sell):
    totp = pyotp.TOTP(config.robin_totp).now()
    print("Current OTP: ", totp)
    login = robin_stocks.login(config.robin_user, config.robin_pwd, mfa_code=totp)

    holdings = robin_stocks.get_open_stock_positions()
    print(buy)
    print(sell)
    for stock in sell:
        stock = stock.strip()
        if stock in holdings:
            quantity = holdings[stock]["quantity"]
            robin_stocks.order_sell_fractional_by_quantity(stock, quantity, 'gfd')

    acc = robin_stocks.load_account_profile()
    print(acc)
    bp = acc["portfolio_cash"]
    print(bp)
    bp = float(bp)
    if bp > 0:
        bpps = bp/len(buy)
        print(bpps)
        for stock in buy:
            order = robin_stocks.order_buy_fractional_by_price(stock, bpps, 'gfd')
            print(order)
    else:
        print("not enough buying power")
    robin_stocks.logout()
Exemple #3
0
    def trade_on_fear_and_greed(self, current_fear_greed_index):

        investors_are_greedy = current_fear_greed_index >= fear_greed.sell_threshold
        investors_are_fearful = current_fear_greed_index <= fear_greed.buy_threshold
        owns_spy = fear_greed.owns_spy()
        current_date_time = datetime.now().strftime("%m/%d/%Y %H:%M:%S")

        if investors_are_greedy and owns_spy:
            # Sell entire SPY position
            price = fear_greed.get_sell_equity_amount()
            result = rh.order_sell_fractional_by_price(fear_greed.symbol,
                                                       price,
                                                       extendedHours=True,
                                                       timeInForce="gfd")

            if result is not None and 'account' in result.keys():
                TradeHistory.update_trade_history(fear_greed.algo,
                                                  current_fear_greed_index,
                                                  fear_greed.symbol, price,
                                                  "sell", current_date_time,
                                                  Client.current_user_id)
            else:
                ui.error(result)
        elif investors_are_fearful and not owns_spy:
            # Buy initial SPY investment or the last sold equity
            price = fear_greed.get_buy_equity_amount(
                TradeHistory.trade_history['trades'])
            result = rh.order_buy_fractional_by_price(fear_greed.symbol,
                                                      price,
                                                      extendedHours=True,
                                                      timeInForce="gfd")

            if result is not None and 'account' in result.keys():
                TradeHistory.update_trade_history(fear_greed.algo,
                                                  current_fear_greed_index,
                                                  fear_greed.symbol, price,
                                                  "buy", current_date_time,
                                                  Client.current_user_id)
            else:
                ui.error(result)
        else:
            # Skip SPY trade because there is not yet a significant fear or greed value
            skipped_dict = {
                "algo": fear_greed.algo,
                "index": current_fear_greed_index,
                "action": "skipped",
                "date": current_date_time,
                "price": "N/A",
                "symbol": "N/A",
                "user_id": Client.current_user_id
            }
            ui.success(skipped_dict)
            return
Exemple #4
0
def buy_stock_fractional(stockName, quantity):
    count = 0
    stockOrdered = False
    while stockOrdered == False and count < orderRetries:
        orderStatus = rs.order_buy_fractional_by_price(stockName,
                                                       quantity,
                                                       timeInForce='gfd',
                                                       priceType='bid_price')
        logging.debug(f'Order Status is {orderStatus}')
        sleep(2)
        stockOrdered = order_status(orderStatus['url'])
        count = count + 1
    # End of While
    if stockOrdered == False:
        logging.info(f'Order not placed. Maximum retries reached')
    # End of If
    return stockOrdered
Exemple #5
0
def rebalance_portfolio(execute_all, test):
    ''' Rebalances your portfolio '''
    if test:
        click.echo('Testing mode ON')
    config = get_config()
    log_in()
    portfolio = Portfolio(config['Asset classes'],
                          float(config['Cash allocation']), test)
    open_orders = rs.get_all_open_stock_orders()
    if len(open_orders) > 0:
        click.echo(
            f'Cannot rebalance: there are already {len(open_orders)} open orders.'
        )
        if click.confirm('Show existing orders?'):
            pp.pprint(open_orders)
        return
    else:
        orders = portfolio.generate_orders()
        if test:
            pp.pprint(orders)
            click.echo(sum([o['Amount'] for o in orders]))
        for i, order in enumerate(orders):
            if execute_all or click.confirm(
                    'Submit '
                    f'${round(order["Amount"], 2)} order for '
                    f'{order["Ticker"]}? ({i+1}/{len(orders)})'):
                if not test:
                    click.echo('Submitting...')
                    result = rs.order_buy_fractional_by_price(
                        order['Ticker'], order['Amount'], timeInForce='gfd')
                    click.echo('Waiting for order to be processed...')
                    while len(rs.get_all_open_stock_orders()) > 0:
                        time.sleep(1)
                click.echo('Order processed.')
            else:
                click.echo('Order not submitted.')
def buy(ticker, amount):
    r = robin.order_buy_fractional_by_price(ticker, int(amount))
    print(r)
Exemple #7
0
    def trade_on_macd(self):
        symbols = [
            "SE", "TTD", "DDOG", "SHOP", "SQ", "DRIP", "CHWY", "OSTK", "NET",
            "CHGG", "PINS", "DAL", "SNAP", "BABA", "NET", "IRBT", "MDB",
            "DKNG", "BYND", "GRUB", "SPOT", "GPS", "INO", "ENPH", "GOLD",
            "IDXX", "CRNC"
        ]

        restricted_stocks = ["AAPL", "WORK", "PLTR", "ROKU", "ETSY"]
        symbols = list(
            (Counter(symbols) - Counter(restricted_stocks)).elements())

        current_date_time = datetime.now().strftime("%m/%d/%Y %H:%M:%S")
        no_transactions = True
        for symbol in symbols:
            df = macd.create_df(symbol)
            df = macd.add_entry_for_today(symbol, df)
            # macd.plot_macd(df, symbol)

            action = macd.get_trade_action(df)
            if action == "buy" and not TradeHistory.already_holding_position(
                    symbol, macd.algo) and False:
                no_transactions = False
                # Buy initial investment or the last sold equity
                price = TradeHistory.get_buy_equity_amount(symbol, "macd")
                result = rh.order_buy_fractional_by_price(symbol,
                                                          price,
                                                          extendedHours=True,
                                                          timeInForce="gfd")
                if result is not None and 'account' in result.keys():
                    TradeHistory.update_trade_history(macd.algo, "N/A", symbol,
                                                      price, "buy",
                                                      current_date_time,
                                                      Client.current_user_id)
                else:
                    ui.error(result)
            elif action == "sell" and TradeHistory.already_holding_position(
                    symbol, macd.algo):
                # Sell entire position
                price = TradeHistory.get_sell_equity_amount(symbol, "macd")
                no_transactions = False
                result = rh.order_sell_fractional_by_price(symbol,
                                                           price,
                                                           extendedHours=True,
                                                           timeInForce="gfd")
                if result is not None and 'account' in result.keys():
                    TradeHistory.update_trade_history(macd.algo, "N/A", symbol,
                                                      price, "sell",
                                                      current_date_time,
                                                      Client.current_user_id)
                else:
                    ui.error(result)
            else:
                continue
        if no_transactions:
            skipped_dict = {
                "algo": macd.algo,
                "index": "N/A",
                "action": "skipped",
                "date": current_date_time,
                "price": "N/A",
                "symbol": "N/A",
                "user_id": Client.current_user_id
            }
            ui.success(skipped_dict)
Exemple #8
0
def buy_frac(amount, symbol):
    ui.success(f'\nBuying ${amount} of {symbol}....\n')
    result = rh.order_buy_fractional_by_price(symbol, amount)
    ui.chec_ref(result)
def buy(symbol, dollars):
    print("Buying $" + str(dollars) + " worth of " + symbol + "...")
    trade = r.order_buy_fractional_by_price(symbol, dollars, 'gfd',
                                            'ask_price', False)
    print(trade)  # comment out when done testing
    return trade['id']