Example #1
0
    def buy( self, ticker ):
        if ( self.available_cash < config[ 'buy_amount_per_trade' ] or self.is_trading_locked ):
            return False
        
        # Values need to be specified to no more precision than listed in min_price_increments.
        # Truncate to 7 decimal places to avoid floating point problems way out at the precision limit
        price = round( floor( self.data.iloc[ -1 ][ ticker ] / self.min_price_increments[ ticker ] ) * self.min_price_increments[ ticker ], 7 )
        
        # How much to buy depends on the configuration
        quantity = ( self.available_cash if ( config[ 'buy_amount_per_trade' ] == 0 ) else config[ 'buy_amount_per_trade' ] ) / price
        quantity = round( floor( quantity / self.min_share_increments[ ticker ] ) * self.min_share_increments[ ticker ], 7 )

        print( 'Buying ' + str( ticker ) + ' ' + str( quantity ) + ' at $' + str( price ) )

        if ( config[ 'trades_enabled' ] and not config[ 'debug_enabled' ] ):
            try:
                buy_info = rh.order_buy_crypto_limit( str( ticker ), quantity, price )

                # Add this new asset to our orders
                self.orders[ buy_info[ 'id' ] ] = asset( ticker, quantity, price, buy_info[ 'id' ] )
            except:
                print( 'Got exception trying to buy, aborting.' )
                return False

        return True
Example #2
0
 def buy(self):
     availableCash = self.getCash()
     if availableCash == -1:
         print(
             "Got an exception checking for available cash, cancelling buy."
         )
         return
     else:
         if self.tradesEnabled == True:
             try:
                 price = self.getCurrentPrice()
                 buyable_qty = self.getBuyingPower(availableCash, price)
                 if buyable_qty > 0:
                     try:
                         print("Buying")
                         result = r.order_buy_crypto_limit(
                             self.coin.name, buyable_qty, price)
                         self.coin.purchasedPrice = price
                         self.coin.numBought = buyable_qty
                         self.coin.lastBuyOrderID = result['id']
                         self.coin.numHeld = self.coin.numBought + self.coin.numHeld
                         self.coin.boughtTime = str(datetime.datetime.now())
                     except:
                         print("Error buying, cancelling buy.")
                         return
                 else:
                     print("Need more funds")
                     return
             except:
                 print("Error getting quote for buy, cancelling buy.")
                 return
         return
Example #3
0
    def buy(self, ticker):
        if self.available_cash == 0 or self.available_cash < config[
                'buy_amount_per_trade'] or self.is_trading_locked:
            return False

        # Retrieve the actual ask price from Robinhood
        if not config['simulate_api_calls']:
            try:
                quote = rh.get_crypto_quote(ticker)
                price = float(quote['ask_price'])
            except:
                print(
                    'Could not retrieve ask price from Robinhood. Using Kraken\'s.'
                )
                price = self.data.iloc[-1][ticker]
        else:
            price = self.data.iloc[-1][ticker]

        # Values need to be specified to no more precision than listed in min_price_increments.
        # Truncate to 7 decimal places to avoid floating point problems way out at the precision limit
        price_precision = round(
            floor(price / self.min_price_increments[ticker]) *
            self.min_price_increments[ticker], 7)

        # How much to buy depends on the configuration
        quantity = (self.available_cash if
                    (config['buy_amount_per_trade'] == 0) else
                    config['buy_amount_per_trade']) / price_precision
        quantity = round(
            floor(quantity / self.min_share_increments[ticker]) *
            self.min_share_increments[ticker], 7)

        if config['trades_enabled'] and not config['simulate_api_calls']:
            try:
                buy_info = rh.order_buy_crypto_limit(str(ticker), quantity,
                                                     price_precision)

                # Add this new asset to our orders
                self.orders[buy_info['id']] = asset(ticker, quantity,
                                                    price_precision,
                                                    buy_info['id'], 'PB')

                print('## Submitted order to buy ' + str(quantity) + ' ' +
                      str(ticker) + ' at $' + str(price_precision))

                if (price != self.data.iloc[-1][ticker]):
                    print('## Price Difference: Kraken $' +
                          str(self.data.iloc[-1][ticker]) + ', Robinhood $ ' +
                          str(price))
            except:
                print('An exception occurred while trying to buy.')
                return False
        else:
            print('## Would have bought ' + str(ticker) + ' ' + str(quantity) +
                  ' at $' + str(price_precision) + ', if trades were enabled')
            return False

        return True
    def buy(self, c, price):
        # currently this is ensuring only 1 position is open at a time
        # we are already in the process of a buy, don't submit another
        if self.boughtIn == True:
            print('Previous buy incomplete.')
            return
        # swapping to this enables multi poistions, but the coin num held needs to be fixed as it is not currently cumulative. For me, if i buy in and the price continues to drop and meet my requirements, I would like to buy more to, and average the buy prices together to get my final sale price of the whole lot.
        # if self.coinState[c].numHeld > 0.0:
        #     print('Already holding ' + self.coinState.name + '. Let\'s resolve that position first.')
        #     return

        availableCash = self.getCash()
        if availableCash == -1:
            print(
                'Got an exception checking for available cash, canceling buy.')
            return

        print('RobinHood says you have ' + str(availableCash) + ' in cash')

        if (availableCash > 1.0):
            minPriceIncrement = self.minPriceIncrements[self.coinState[c].name]
            # price needs to be specified to no more precision than listed in minPriceIncrement. Truncate to 7 decimal places to avoid floating point problems way out at the precision limit
            price = round(self.roundDown(price, minPriceIncrement), 7)
            shares = (availableCash - .25) / price
            minShareIncrement = self.minIncrements[self.coinState[c].name]
            shares = round(self.roundDown(shares, minShareIncrement), 8)
            sellAt = price + (price * self.sellAboveBuyPrice)
            print('Buying ' + str(shares) + ' shares of ' + self.coinList[c] +
                  ' at ' + str(price) + ' selling at ' + str(round(sellAt, 2)))

            if self.tradesEnabled == True:
                try:
                    buyResult = r.order_buy_crypto_limit(
                        str(self.coinList[c]), shares, price)
                    self.coinState[c].lastBuyOrderID = buyResult['id']
                    print(str(buyResult))
                except:
                    print('Got exception trying to buy, cancelling.')
                    return

                print('Bought ' + str(shares) + ' shares of ' +
                      self.coinList[c] + ' at ' + str(price) + ' selling at ' +
                      str(round(sellAt, 2)))
                self.coinState[c].purchasedPrice = price
                self.coinState[c].numHeld = shares
                self.coinState[c].timeBought = str(datetime.datetime.now())
                self.coinState[c].numBought = shares
                self.boughtIn = True

        return
    def buy(self, c, price):

        #we are already in the process of a buy, don't submit another
        if self.boughtIn == True:
            print("Previous buy incomplete.")
            return

        availableCash = self.getCash()
        if availableCash == -1:
            print(
                "Got an exception checking for available cash, canceling buy.")
            return

        print("RobinHood says you have " + str(availableCash) + " in cash")

        if (availableCash > 1.0):
            minPriceIncrement = self.minPriceIncrements[self.coinState[c].name]
            #price needs to be specified to no more precision than listed in minPriceIncrement. Truncate to 7 decimal places to avoid floating point problems way out at the precision limit
            price = round(self.roundDown(price, minPriceIncrement), 7)
            shares = (availableCash - .25) / price
            minShareIncrement = self.minIncrements[self.coinState[c].name]
            shares = round(self.roundDown(shares, minShareIncrement), 8)
            sellAt = price + (price * self.sellAboveBuyPrice)
            print("Buying " + str(shares) + " shares of " + self.coinList[c] +
                  " at " + str(price) + " selling at " + str(round(sellAt, 2)))

            if self.tradesEnabled == True:
                try:
                    buyResult = r.order_buy_crypto_limit(
                        str(self.coinList[c]), shares, price)
                    self.coinState[c].lastBuyOrderID = buyResult['id']
                    self.output(str(buyResult))
                except:
                    print("Got exception trying to buy, cancelling.")
                    return

                msg = "LiveBot: Bought " + str(
                    shares) + " shares of " + self.coinList[c] + " at " + str(
                        price) + " selling at " + str(round(sellAt, 2))
                self.output(msg)
                self.coinState[c].purchasedPrice = price
                self.coinState[c].numHeld = shares
                self.coinState[c].timeBought = str(datetime.datetime.now())
                self.coinState[c].numBought = shares
                self.boughtIn = True

        return
Example #6
0
    def buy(self, ticker):
        if (self.available_cash == 0
                or self.available_cash < config['buy_amount_per_trade']
                or self.is_trading_locked):
            return False

        # Values need to be specified to no more precision than listed in min_price_increments.
        # Truncate to 7 decimal places to avoid floating point problems way out at the precision limit
        price = round(
            floor(self.data.iloc[-1][ticker] /
                  self.min_price_increments[ticker]) *
            self.min_price_increments[ticker], 7)

        # How much to buy depends on the configuration
        quantity = (self.available_cash if
                    (config['buy_amount_per_trade']
                     == 0) else config['buy_amount_per_trade']) / price
        quantity = round(
            floor(quantity / self.min_share_increments[ticker]) *
            self.min_share_increments[ticker], 7)

        if (config['trades_enabled'] and not config['simulate_api_calls']):
            try:
                buy_info = rh.order_buy_crypto_limit(str(ticker), quantity,
                                                     price)

                # Add this new asset to our orders
                self.orders[buy_info['id']] = asset(ticker, quantity, price,
                                                    buy_info['id'])

                # Update the available cash for trading
                self.available_cash = round(
                    self.available_cash - quantity * price, 3)

                print('## Bought ' + str(ticker) + ' ' + str(quantity) +
                      ' at $' + str(price))
            except:
                print('An exception occurred while trying to buy.')
                return False
        else:
            print('## Would have bought ' + str(ticker) + ' ' + str(quantity) +
                  ' at $' + str(price) + ', if trades were enabled')
            return False

        return True
Example #7
0
 def order_buy_crypto_limit(self, symbol, quantity, limitPrice):
     self = r.order_buy_crypto_limit(symbol, quantity, limitPrice)
Example #8
0
    def trigger_tx(self,
                   symbol,
                   quantity=None,
                   price=None,
                   side=None,
                   cash_on_hand=None,
                   quantity_on_hand=None,
                   in_dollars=False):
        """ Attempts to make a trade. Returns None if no trade was made. """
        info = None
        if side not in {"buy", "sell"}:
            raise Exception("side should be 'buy' or 'sell'")
        if side == 'buy':
            if cash_on_hand is None:
                cash_on_hand = self.check_cash_on_hand(symbol="USD")
            max_allocation = MAX_ALLOCATION[symbol]
            if MAX_ALLOCATION_IS_PERCENT:
                max_allocation = (max_allocation / 100) * self.total_value
            if cash_on_hand < MIN_DOLLARS_PER_TRADE: return
            if price is None:
                raise Exception(
                    "Price cannot be None. Calcuate a price or change the code to calculate a default price."
                )
            if symbol == 'DOGE':
                price = round(price, 6)
            else:
                price = round(price, 2)

            if quantity is None:
                # price is not None and quantity is None
                # so calculate a quantity:

                buy_amount = min(cash_on_hand, MAX_DOLLARS_PER_BUY[symbol],
                                 max_allocation - self.symbol_value[symbol])
                if cash_on_hand - buy_amount < MIN_DOLLARS_PER_TRADE:
                    # If buy would leave us with less cash than we can trade with, just use all of it.
                    buy_amount = cash_on_hand

                quantity = round(buy_amount / price, self.ndigits[symbol])
                info = rh.order_buy_crypto_limit(symbol, quantity, price)
                #if symbol == 'DOGE':
                #   info = rh.order_buy_crypto_by_price(symbol, round(buy_amount, self.ndigits[symbol]))
                #   quantity = round(buy_amount/price , self.ndigits[symbol])
                #   info = rh.order_buy_crypto_limit(symbol, quantity, price)
                #else:
                #    #info = rh.order_buy_crypto_by_price(symbol, buy_amount)
            else:
                info = rh.order_buy_crypto_limit(symbol, quantity, price)

        else:  # side == 'sell'
            if price is None:
                price = float(rh.get_crypto_quote(symbol)['bid_price'])
            if symbol == 'DOGE':
                price = round(price, 8)
            else:
                price = round(price, 2)
            if quantity_on_hand is None:
                quantity_on_hand = self.quantity_on_hand[symbol]
                # raise Exception("quantity_on_hand cannot be None. Calcuate a quantity or change the code to calculate a default price.")
            if quantity_on_hand * price < MIN_DOLLARS_PER_TRADE:
                return
            if in_dollars:
                info = rh.order_sell_crypto_by_price(symbol, quantity)
            else:
                if quantity is None:
                    if in_dollars: raise NotImplementedError
                    quantity = round(MAX_DOLLARS_PER_SELL[symbol] / price,
                                     self.ndigits[symbol])
                    if price * quantity_on_hand < MAX_DOLLARS_PER_SELL[
                            symbol] or price * (quantity_on_hand - quantity
                                                ) < MIN_DOLLARS_PER_TRADE:
                        quantity = quantity_on_hand
                else:
                    pass
                info = rh.order_sell_crypto_by_quantity(symbol, quantity)

        retval = info
        if info is not None:
            if 'account_id' in info.keys():
                self.disp_warn_feed.feedlines(
                    f"{side.capitalize()}ing: {quantity} {symbol.upper()} at limit price ${price}"
                )
            with Capturing() as output:
                print(
                    f"Trade executed: symbol = {symbol}, quantity = {quantity}, price = {price}, side = {side}\n"
                )
                print(info)
            try:
                self.order_ids[time.time()] = info['id']
                # self.bump_rsi(symbol,side)
            except KeyError:
                retval = None
            logging.info(output)
        return retval