Example #1
0
 def test_crypto_info(self):
     crypto = r.get_crypto_info(self.bitcoin, info=None)
     assert ('asset_currency' in crypto)
     assert ('display_only' in crypto)
     assert ('id' in crypto)
     assert ('max_order_size' in crypto)
     assert ('min_order_size' in crypto)
     assert ('min_order_price_increment' in crypto)
     assert ('min_order_quantity_increment' in crypto)
     assert ('name' in crypto)
     assert ('quote_currency' in crypto)
     assert ('symbol' in crypto)
     assert ('tradability' in crypto)
     crypto = r.get_crypto_info(self.stock, info=None)
     assert (crypto == None)
    def getIncrements(self):

        self.minIncrements = {}
        self.minPriceIncrements = {}

        #also need min_order_price_increment

        for c in range(0, len(self.coinList)):
            code = self.coinList[c]

            try:
                result = r.get_crypto_info(code)
                inc = result['min_order_quantity_increment']
                p_inc = result['min_order_price_increment']
            except:
                print(
                    "Failed to get increments from RobinHood. Are you connected to the internet? Exiting."
                )
                exit()

            self.minIncrements.update({code: float(inc)})
            self.minPriceIncrements.update({code: float(p_inc)})

        print("Minimum sale increments:")
        print(self.minIncrements)

        print("Minimum price increments:")
        print(self.minPriceIncrements)
Example #3
0
 def getIncrements(self):
     try:
         result = r.get_crypto_info(self.coin.name)
         self.minCoinIncrement = float(
             result['min_order_quantity_increment'])
         self.minPriceIncrement = float(result['min_order_price_increment'])
         self.minOrderSize = float(result['min_order_size'])
     except:
         print("Problem getting crypto information")
Example #4
0
    async def run(self):
        r.login(os.getenv('ROBINHOOD_USERNAME'),
                os.getenv('ROBINHOOD_PASSWORD'))
        crypto = self.content.replace('$crypto_price ', '').upper().split()
        for c in crypto:
            curr = r.get_crypto_info(c)
            if not curr:
                message = "❌ '" + c + "' Crypto symbol doesn't exist."
                self.response.add_response(message)
                continue
            for d in [curr]:
                name = d['name']
                symbol = c
                price = r.crypto.get_crypto_quote(c)
                for p in [price]:
                    cost = p['ask_price']
                message = name + ' (' + symbol + ') is currently worth' + '${:,.2f}'.format(
                    float(cost))
                self.response.add_response(message)

        if len(self.response.response) == 0:
            self.response.set_error_response(0)
        self.response.done = True
Example #5
0
    def __init__(self):
        # Set Pandas to output all columns in the dataframe
        pd.set_option('display.max_columns', None)
        pd.set_option('display.width', 300)

        print('-- Configuration ------------------------')
        for c in self.default_config:
            isDefined = config.get(c)
            if not isDefined:
                config[c] = self.default_config[c]

        if not config['username'] or not config['password']:
            print('RobinHood credentials not found in config file. Aborting.')
            exit()

        if config['rsi_period'] > config['moving_average_periods']['sma_fast']:
            self.min_consecutive_samples = config['rsi_period']
        else:
            self.min_consecutive_samples = config['moving_average_periods'][
                'sma_fast']

        for a_key, a_value in config.items():
            if (a_key == 'username' or a_key == 'password'):
                continue

            print(a_key.replace('_', ' ').capitalize(), ': ', a_value, sep='')

        print('-- Init Environment ---------------------')

        # Initialize folders where to store data and charts
        if not path.exists('pickle'):
            makedirs('pickle')

        if not path.exists('charts'):
            makedirs('charts')

        if path.exists('pickle/orders.pickle'):
            # Load state
            print('Loading saved orders')
            with open('pickle/orders.pickle', 'rb') as f:
                self.orders = pickle.load(f)
        else:
            # Start from scratch
            print('No state saved, starting from scratch')

        # Load data points
        if path.exists('pickle/dataframe.pickle'):
            print('Loading saved dataset')
            self.data = pd.read_pickle('pickle/dataframe.pickle')

        # Connect to Robinhood
        if not config['simulate_api_calls']:
            try:
                print('Logging in to Robinhood')
                rh_response = rh.login(config['username'], config['password'])
            except:
                print('Got exception while attempting to log into Robinhood.')
                exit()

        # Download Robinhood parameters
        for a_robinhood_ticker in config['ticker_list'].values():
            if not config['simulate_api_calls']:
                try:
                    result = rh.get_crypto_info(a_robinhood_ticker)
                    self.min_share_increments.update({
                        a_robinhood_ticker:
                        float(result['min_order_quantity_increment'])
                    })
                    self.min_price_increments.update({
                        a_robinhood_ticker:
                        float(result['min_order_price_increment'])
                    })
                except:
                    print('Failed to get increments from RobinHood.')
                    exit()
            else:
                self.min_share_increments.update({a_robinhood_ticker: 0.0001})
                self.min_price_increments.update({a_robinhood_ticker: 0.0001})

        # How much cash do we have?
        self.update_available_cash()

        # Install signal handlers
        signal.signal(signal.SIGTERM, self.handle_exit)
        signal.signal(signal.SIGINT, self.handle_exit)

        print('Bot Ready')

        return
Example #6
0
    def __init__( self ):
        # Set Pandas to output all columns in the dataframe
        pd.set_option( 'display.max_columns', None )
        pd.set_option( 'display.width', 300 )

        print( '-- Configuration ------------------------' )
        for c in self.default_config:
            isDefined = config.get( c )
            if ( not isDefined ):
                config[ c ] = self.default_config[ c ]

        if ( not config[ 'username' ] or not config[ 'password' ] ):
            print( 'RobinHood credentials not found in config file. Aborting.' )
            exit()

        if ( config[ 'rsi_period' ] > config[ 'moving_average_periods' ][ 'sma_fast' ] ):
            self.min_consecutive_samples = config[ 'rsi_period' ]
        else:
            self.min_consecutive_samples = config[ 'moving_average_periods' ][ 'sma_fast' ]
        
        for a_key, a_value in config.items():
            if ( a_key == 'username' or a_key == 'password' ):
                continue

            print( a_key.replace( '_', ' ' ).capitalize(), ': ', a_value, sep='' )

        print( '-- End Configuration --------------------' )

        if path.exists( 'orders.pickle' ):
            # Load state
            print( 'Loading previously saved state' )
            with open( 'orders.pickle', 'rb' ) as f:
                self.orders = pickle.load( f )
        else:
            # Start from scratch
            print( 'No state saved, starting from scratch' )

        # Load data points
        if ( path.exists( 'dataframe.pickle' ) ):
            self.data = pd.read_pickle( 'dataframe.pickle' )
            
            # Only track up to a fixed amount of data points
            self.data = self.data.tail( config[ 'max_data_rows' ] - 1 )
        else:
            # Download historical data from Kraken
            column_names = [ 'timestamp' ]

            for a_robinhood_ticker in config[ 'ticker_list' ].values():
                column_names.append( a_robinhood_ticker )

            self.data = pd.DataFrame( columns = column_names )

            for a_kraken_ticker, a_robinhood_ticker in config[ 'ticker_list' ].items():
                try:
                    result = get_json( 'https://api.kraken.com/0/public/OHLC?interval=' + str( config[ 'minutes_between_updates' ] ) + '&pair=' + a_kraken_ticker ).json()
                    historical_data = pd.DataFrame( result[ 'result' ][ a_kraken_ticker ] )
                    historical_data = historical_data[ [ 0, 1 ] ]
                    
                    # Be nice to the Kraken API
                    sleep( 3 )
                except:
                    print( 'An exception occurred retrieving historical data from Kraken.' )

                # Convert timestamps
                self.data[ 'timestamp' ] = [ datetime.fromtimestamp( x ).strftime( "%Y-%m-%d %H:%M" ) for x in historical_data[ 0 ] ] 

                # Copy the data
                self.data[ a_robinhood_ticker ] = [ round( float( x ), 3 ) for x in historical_data[ 1 ] ]

                # Calculate the indicators
                self.data[ a_robinhood_ticker + '_SMA_F' ] = self.data[ a_robinhood_ticker ].shift( 1 ).rolling( window = config[ 'moving_average_periods' ][ 'sma_fast' ] ).mean()
                self.data[ a_robinhood_ticker + '_SMA_S' ] = self.data[ a_robinhood_ticker ].shift( 1 ).rolling( window = config[ 'moving_average_periods' ][ 'sma_slow' ] ).mean()
                self.data[ a_robinhood_ticker + '_RSI' ] = RSI( self.data[ a_robinhood_ticker ].values, timeperiod = config[ 'rsi_period' ] )
                self.data[ a_robinhood_ticker + '_MACD' ], self.data[ a_robinhood_ticker + '_MACD_S' ], macd_hist = MACD( self.data[ a_robinhood_ticker ].values, fastperiod = config[ 'moving_average_periods' ][ 'macd_fast' ], slowperiod = config[ 'moving_average_periods' ][ 'macd_slow' ], signalperiod = config[ 'moving_average_periods' ][ 'macd_signal' ] )

        # Connect to RobinHood
        if ( not config[ 'debug_enabled' ] ):
            try:
                rh_response = rh.login( config[ 'username' ], config[ 'password' ] )
            except:
                print( 'Got exception while attempting to log into RobinHood.' )
                exit()

        # Download RobinHood parameters
        for a_robinhood_ticker in config[ 'ticker_list' ].values():
            if ( not config[ 'debug_enabled' ] ):
                try:
                    result = rh.get_crypto_info( a_robinhood_ticker )
                    s_inc = result[ 'min_order_quantity_increment' ]
                    p_inc = result[ 'min_order_price_increment' ]
                except:
                    print( 'Failed to get increments from RobinHood.' )
                    exit()
            else:
                s_inc = 0.0001
                p_inc = 0.0001

            self.min_share_increments.update( { a_robinhood_ticker: float( s_inc ) } )
            self.min_price_increments.update( { a_robinhood_ticker: float( p_inc ) } )

        # Initialize the available_cash amount
        self.available_cash = self.get_available_cash()

        print( 'Bot Ready' )

        return