Пример #1
0
 def get_open_options(self):
     positions = []
     for each_pos in rs.get_open_option_positions():
         if each_pos['quantity'] != "0.0000":
             url = each_pos['option']
             data = helper.request_get(url)
             mkt_data = self.rs.get_option_market_data_by_id(
                 url.split('/')[-2])
             # fill out the data
             each_pos['optype'] = data['type']
             each_pos['expiration_date'] = data['expiration_date']
             each_pos['created_at'] = data['created_at']
             each_pos['strike_price'] = data['strike_price']
             price_tag = 'ask_price' if each_pos[
                 'type'] is 'short' else 'bid_price'
             qty_tag = 'pending_buy_quantity' if each_pos[
                 'type'] is 'short' else 'pending_sell_quantity'
             each_pos['curr_price'] = mkt_data[price_tag]
             # each_pos['change'] = mkt_data[]
             if each_pos['type'] is 'short':
                 each_pos['change'] = (
                     float(mkt_data['ask_price']) -
                     float(mkt_data['previous_close_price']))
             else:
                 each_pos['change'] = float(mkt_data['bid_price']) - float(
                     mkt_data['previous_close_price'])
             each_pos['tradable_qty'] = float(each_pos['quantity']) - float(
                 each_pos[qty_tag])
             #    sum([float(each_pos[x]) for x in each_pos.keys() if 'pending_' in x])
             positions.append(each_pos)
     return positions
Пример #2
0
def get_open_urls():

    positions = r.get_open_option_positions()

    urls = []
    for position in positions:
        urls.append(position['url'])

    return urls
Пример #3
0
def run():
    f.add_event_log('function[run] Robinhood Auto_trader Start')

    market: str = find_variable('market')
    symbol: str = find_variable('symbol')
    # check if market is currently open
    f.add_event_log('function[run] Market Open: {0}'.format(
        f.is_market_open(market)))

    if f.is_market_open(market):
        f.add_event_log('function[run] Market Open')

        # login
        f.account_login()
        # check spread positions
        if 1 > len(rs.get_open_option_positions()):
            purchase(symbol)

        portfolio_credit_spreads: list[
            CreditSpread] = f.get_credit_spreads_portfolio()

        # if list is empty place an order && sufficient balance

        # check age of the spreads
        for credit_spread in portfolio_credit_spreads:
            f.add_event_log('function[run] Check purchase date')
            purchase_date = d.datetime.strptime(credit_spread.purchase_date,
                                                '%Y-%m-%d')
            if (d.datetime.today() - purchase_date).days >= 30:
                f.add_event_log(
                    'function[run] purchase_date: {0} is older than 30 day. Sell position.'
                )
                f.sell_loop(credit_spread)

        # check update config file
        if len(portfolio_credit_spreads) > 0:
            # stop_loss
            f.stop_loss(portfolio_credit_spreads, market)
        # log out
        rs.logout()
        f.add_event_log('function[run] Account Logout')
    f.add_event_log('function[run] Robinhood Auto_trader Shutdown.')
Пример #4
0
def get_curr_options():

    print("Current Options Trades: ")
    open_positions = r.get_open_option_positions()

    for option in open_positions:

        name = option['chain_symbol']

        num_contracts = float(option['quantity'])
        multiplier = num_contracts * 100

        avg_price = float(option['average_price'])

        op_id = option['option_id']

        op_data = r.options.get_option_instrument_data_by_id(op_id)

        ed = datetime.strptime(op_data['expiration_date'], '%Y-%m-%d').date()

        td = datetime.today().strftime('%Y-%m-%d')
        td = datetime.strptime(td, '%Y-%m-%d').date()

        time_left = ed - td
        days_left = time_left.days

        op_type = op_data['type']

        strike_price = float((op_data['strike_price']))

        curr_option_data = r.options.get_option_market_data(
            name, op_data['expiration_date'], strike_price, op_type)

        curr_price = round(
            float(curr_option_data[0][0]['adjusted_mark_price']) * multiplier)

        profit = curr_price - avg_price

        print("Ticker: " + name)
        print("Average Cost: $" + str(avg_price))
        print("Current Price: $" + str(curr_price))
        if (profit < 0):
            print("Profit" + fg(255, 10, 10) + " $" + str(profit) + fg.rs)
        else:
            print("Profit:" + fg(0, 255, 0) + " $" + str(profit) + fg.rs)
        print("Time Until Expiration: " + str(days_left) + " Days")

        data = r.options.get_option_historicals(name,
                                                op_data['expiration_date'],
                                                op_data['strike_price'],
                                                op_type, '5minute', 'day')
        converted = convert_list(data)
        print(data)

        dataframe = pd.DataFrame(converted)

        close_prices = dataframe['close_price'].astype(float)

        x = range(close_prices.count())

        plt.plot(x, close_prices)

        plt.show()
Пример #5
0
    def get_current_options(self):
        orders = r.get_open_option_positions()

        return orders
Пример #6
0
    def rh_pull_portfolio_data(user_id, passwd):
        r.login(username=user_id, password=passwd)

        if DbAccess.is_update_needed():
            obj = portfolio_summary.objects.all()
            if not obj:
                obj = portfolio_summary()
                obj.timestamp = timezone.now()
            else:
                obj = obj[0]
            obj.portfolio_cash  = float(profiles.load_account_profile()['portfolio_cash'])
            obj.save()

            # remove current entries
            stocks_held.objects.all().delete()
            # get current owned securites and save to db
            positions_data = r.get_open_stock_positions()
            for item in positions_data:
                quantity = float(item['quantity'])
                if not quantity:
                    continue
                # check if instrument is present in robinhood_traded_stocks table
                obj                     = stocks_held()
                obj.symbol, obj.name    = RhWrapper.rh_pull_symbol_from_instrument_url(item['instrument'])
                obj.quantity            = quantity
                obj.average_price       = float(item['average_buy_price'])
                obj.latest_price        = float(r.get_latest_price(obj.symbol)[0])
                obj.open_price          = float(r.get_fundamentals(obj.symbol)[0]['open'])
                try:
                    obj.prev_close_price    = float(StockUtils.getStockInfo(obj.symbol)['previousClose'])
                except Exception as e:
                    logging.error(str(e) + ' encountered when fetching yahoo data for ' + obj.symbol)
                    obj.prev_close_price = obj.open_price
                obj.save()

            # remove current entries
            options_held.objects.all().delete()
            # get current owned securites and save to db
            options_position_data = r.get_open_option_positions()
            for item in options_position_data:
                quantity = float(item['quantity'])
                if not quantity:
                    continue
                obj                        = options_held()
                obj.option_id              = item['option_id']
                contract_into              = r.get_option_instrument_data_by_id(obj.option_id)
                obj.strike_price           = float(contract_into['strike_price'])
                obj.expiration_date        = contract_into['expiration_date']
                obj.option_type            = contract_into['type']
                obj.symbol                 = item['chain_symbol']
                obj.trade_value_multiplier = float(item['trade_value_multiplier'])
                obj.average_price          = float(item['average_price']) / obj.trade_value_multiplier
                obj.quantity               = float(item['quantity'])
                # adjust value for sold calls
                if obj.average_price < 0:
                    obj.average_price      = (-1) * obj.average_price
                    obj.quantity           = (-1) * obj.quantity
                market_data                = r.get_option_market_data_by_id(obj.option_id)
                obj.previous_close_price   = float(market_data['previous_close_price'])
                obj.current_price          = float(market_data['adjusted_mark_price'])
                # print('symbol: %5s strike_price: %7.2f option_type: %4s expiration_date: %12s trade_value_multiplier: %d average_price: %7.2f quantity: %d previous_close_price: %7.2f current_price: %7.2f' % (obj.symbol, obj.strike_price, obj.option_type, obj.expiration_date, obj.trade_value_multiplier, obj.average_price, obj.quantity, obj.previous_close_price, obj.current_price))
                obj.save()