Skip to content

Instantly share code, notes, and snippets.

@JasonRBowling
Created December 12, 2020 20:32
Show Gist options
  • Save JasonRBowling/088ecbdd0f52ce8422e819400c0c7dda to your computer and use it in GitHub Desktop.
Save JasonRBowling/088ecbdd0f52ce8422e819400c0c7dda to your computer and use it in GitHub Desktop.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment