def triggeredUp(symbObj, curPrice, buyPrice, closePrice, maxPrice, sellUpDn, latestTrades): global gainers print("Starting thread for " + symbObj['symbol']) while ((curPrice / buyPrice >= maxPrice / buyPrice * sellUpDn or curPrice / closePrice >= maxPrice / closePrice * sellUpDn) and a.timeTillClose() >= 30): curPrice = a.getPrice(symbObj['symbol']) maxPrice = max(maxPrice, curPrice) print(symbObj['symbol'] + " - " + str(round(curPrice / buyPrice, 2)) + ":" + str(round(maxPrice / buyPrice * sellUpDn, 2)) + " - " + str(round(curPrice / closePrice, 2)) + ":" + str(round(maxPrice / closePrice, 2))) a.o.time.sleep(3) print(a.createOrder("sell", symbObj['qty'], symbObj['symbol'])) latestTrades[symbObj['symbol']] = { "tradeDate": str(a.o.dt.date.today()), "tradeType": "sell", "buyPrice": 0, #reset the avgBuyPrice to 0 after a sell "shouldSell": False } with open(a.o.c['latestTradesFile'], "w") as f: f.write(a.o.json.dumps(latestTrades, indent=2)) #remove from gainers in case it sells after updateStockList has run if (symbObj['symbol'] in gainers): gainers.remove(symbOjb['symbol'])
def mainAlgo(): global gStocksUpdated #this only gets set once in this function - after market is closed isMaster = a.o.c[ 'isMaster'] #is the master or a slave program - a slave will relinquish control to a master if the master is running, but will take over if the master dies minBuyPow = a.o.c['minBuyPow'] #min buying power to hold onto if.. buyPowMargin = a.o.c['buyPowMargin'] # actual buy pow > this*minBuyPow minDolPerStock = a.o.c[ 'minDolPerStock'] #min $ to dedicate to an individual stock minPortVal = a.o.c[ 'minPortVal'] #stop trading if portfolio reaches this amount sellUp = a.o.c[ 'sellUp'] #trigger point. Compare to when it was bought, additional logic to see if it goes higher sellDn = a.o.c['sellDn'] #limit loss sellUpDn = a.o.c[ 'sellUpDn'] #sell if it triggers sellUp then drops sufficiently #init the stock list if we rereun during the week if (a.o.dt.date.today().weekday() < 5): #not saturday or sunday with open(a.o.c['latestTradesFile'], "r") as f: latestTrades = a.o.json.loads(f.read()) portVal = float(a.getAcct()['portfolio_value']) while portVal > minPortVal: #TODO: adjust minPortVal to be some % of max port val random.shuffle( gainers ) #randomize list so when buying new ones, they won't always choose the top of the original list #TODO: if slave, check here to see if master is back online if (not isMaster and a.o.masterLives()): a.o.time.sleep(3600) else: #is the master or the master is dead if (a.marketIsOpen()): print("\nMarket is open") with open(a.o.c['latestTradesFile'], "r") as f: latestTrades = a.o.json.loads(f.read()) acctInfo = a.getAcct() stocksUpdated = gStocksUpdated #set the local value to the global value portVal = float(acctInfo['portfolio_value']) print( f"Portfolio val is ${round(portVal,2)}. Buying power is ${round(float(acctInfo['buying_power']),2)}, ${max(float(round(float(acctInfo['buying_power']),2))-minBuyPow*buyPowMargin,0)} available" ) #only update the stock list and buy stocks if the gainers list is done being populated/updated and that we actually have enough money to buy things if ('listUpdate' not in [t.getName() for t in threading.enumerate()] and float(acctInfo['buying_power']) >= minDolPerStock): #update the stock list 20 minutes before close, if it's not already updated if ((not stocksUpdated) and a.timeTillClose() <= a.o.c['updateListTime'] * 60): updateThread = threading.Thread( target=updateStockList) #init the thread updateThread.setName( 'listUpdate') #set the name to the stock symb updateThread.start() #start the thread #check here if the time is close to close - in the function, check that the requested stock didn't peak today if ( a.timeTillClose() <= a.o.c['buyTime'] * 60 ): #must be within some time before close to start buying and buying thread cannot be running already #Use this for non-threading: check2buy(latestTrades, minBuyPow, buyPowMargin, minDolPerStock) ''' #use this for threading: if('buying' not in [t.getName() for t in threading.enumerate()] and a.timeTillClose()<=a.o.c['buyTime']*60): #must be within some time before close to start buying and buying thread cannot be running already buyThread = threading.Thread(target=check2buy, args=(latestTrades, minBuyPow, buyPowMargin, dolPerStock)) #init the thread buyThread.setName('buying') #set the name to the stock symb a.o.buyThread.start() #start the thread ''' print("Tradable Stocks:") check2sell(a.getPos(), latestTrades, sellDn, sellUp, sellUpDn) ''' with open(a.o.c['webDataFile'],'w') as f: f.write(a.o.json.dumps({"portVal":round(portVal,2),"updated":a.o.dt.datetime.utcnow().strftime("%Y-%m-%d, %H:%M")+" UTC"})) ''' a.o.time.sleep(60) else: print("Market closed.") gStocksUpdated = False p = a.getPos() for e in p: print(f"{e['symbol']} marked to sell? ", end="") news = str(ns.scrape(e['symbol'])).lower() #add field to latest trades if it's marked to be sold shouldSell = "reverse stock split" in news or "reverse-stock-split" in news #sell before a reverse stock split print(shouldSell) with open(a.o.c['latestTradesFile'], "r") as f: latestTrades = a.o.json.loads(f.read()) try: latestTrades[e['symbol']]['shouldSell'] = shouldSell except Exception: latestTrades[e['symbol']] = {'shouldSell': shouldSell} with open(a.o.c['latestTradesFile'], "w") as f: f.write(a.o.json.dumps(latestTrades, indent=2)) if (a.o.dt.date.today().weekday() == 4): #if it's friday print("Removing saved csv files" ) #delete all csv files in stockDataDir for f in glob(a.o.c['stockDataDir'] + "*.csv"): a.o.os.unlink(f) tto = a.timeTillOpen() print("Opening in " + str(round(tto / 3600, 2)) + " hours") a.o.time.sleep(tto)
def main(): global gStocksUpdated #this only gets set once in this function - after market is closed isMaster = bool( a.o.c['Master Info']['isMaster'] ) #is the master or a slave program - a slave will relinquish control to a master if the master is running, but will take over if the master dies minBuyPow = float(a.o.c['Account Params'] ['minBuyPow']) #min buying power to hold onto if.. buyPowMargin = float(a.o.c['Account Params'] ['buyPowMargin']) # actual buy pow > this*minBuyPow minDolPerStock = float( a.o.c['Account Params'] ['minDolPerStock']) #min $ to dedicate to an individual stock minPortVal = float( a.o.c['Account Params'] ['minPortVal']) #stop trading if portfolio reaches this amount sellUp = float( a.o.c['Sell Params']['sellUp'] ) #trigger point. Compare to when it was bought, additional logic to see if it goes higher sellDn = float(a.o.c['Sell Params']['sellDn']) #limit loss sellUpDn = float( a.o.c['Sell Params'] ['sellUpDn']) #sell if it triggers sellUp then drops sufficiently #init the stock list if we rereun during the week if (a.o.dt.date.today().weekday() < 5): #not saturday or sunday with open(a.o.c['File Locations']['latestTradesFile'], "r") as f: latestTrades = a.o.json.loads(f.read()) portVal = float(a.getAcct()['portfolio_value']) while portVal > minPortVal: #TODO: adjust minPortVal to be some % of max port val (based on closing values) #TODO: if slave, check here to see if master is back online if (not isMaster and a.o.masterLives()): a.o.time.sleep(3600) else: #is the master or the master is dead if (a.marketIsOpen()): print("\nMarket is open") with open(a.o.c['File Locations']['latestTradesFile'], "r") as f: latestTrades = a.o.json.loads(f.read()) pos = a.getPos() acctInfo = a.getAcct() #TODO: move this to after the check2Buy part to show updated port/cash values portVal = float(acctInfo['portfolio_value']) print( f"Portfolio val is ${round(portVal,2)}. Buying power is ${round(float(acctInfo['cash']),2)}, ${round(float(acctInfo['cash']) if float(acctInfo['cash'])<=minBuyPow else max(0,float(acctInfo['cash'])-minBuyPow*buyPowMargin),2)} available" ) #if the program is started while the market is open, update the stock list immediately (do not try to run it again if it's already running) if (not gStocksUpdated and 'markUpdate' not in [t.getName() for t in threading.enumerate()]): #mark stocks to be sold, then update the stock list markUpdateThread = threading.Thread( target=markAndUpdate) #init the thread markUpdateThread.setName( 'markUpdate') #set the name to the stock symb markUpdateThread.start() #start the thread #only update the stock list and buy stocks if the gainers list is done being populated/updated and that we actually have enough money to buy things if ('listUpdate' not in [t.getName() for t in threading.enumerate()] and float(acctInfo['cash']) >= minDolPerStock): #check here if the time is close to close - in the function, check that the requested stock didn't peak today if ( a.timeTillClose() <= float(a.o.c['Time Params']['buyTime']) * 60 ): #must be within some time before close to start buying and buying thread cannot be running already #Use this for non-threading: check2buyDJ(latestTrades, pos, minBuyPow, buyPowMargin, minDolPerStock) ''' #use this for threading: if('buying' not in [t.getName() for t in threading.enumerate()] and a.timeTillClose()<=a.o.c['Time Params']['buyTime']*60): #must be within some time before close to start buying and buying thread cannot be running already buyThread = threading.Thread(target=check2buyDJ, args=(latestTrades, minBuyPow, buyPowMargin, dolPerStock)) #init the thread buyThread.setName('buying') #set the name to the stock symb a.o.buyThread.start() #start the thread ''' # print("Tradable Stocks:") check2sellDJ(pos, latestTrades, sellDn, sellUp, sellUpDn) ''' with open(a.o.c['File Locations']['webDataFile'],'w') as f: f.write(a.o.json.dumps({"portVal":round(portVal,2),"updated":a.o.dt.datetime.utcnow().strftime("%Y-%m-%d, %H:%M")+" UTC"})) ''' a.o.time.sleep(60) else: print("Market closed.") gStocksUpdated = False if (a.o.dt.date.today().weekday() == 4 and a.o.dt.datetime.now().time() > a.o.dt.time(12)): #if it's friday afternoon print("Removing saved csv files" ) #delete all csv files in stockDataDir for f in glob(a.o.c['File Locations']['stockDataDir'] + "*.csv"): a.o.os.unlink(f) tto = a.timeTillOpen() print(f"Opening in {round(tto/3600,2)} hours") #at n minutes or later before market opens, update the stock list. If market is open, update immediately if (tto <= float(a.o.c['Time Params']['updateListTime']) * 60): #mark stocks to be sold, then update the stock list markUpdateThread = threading.Thread( target=markAndUpdate) #init the thread markUpdateThread.setName( 'markUpdate') #set the name to the stock symb markUpdateThread.start() #start the thread a.o.time.sleep( tto ) #we'll probably lose ~1 second of market time in the morning else: print( f"Updating list in {round((tto-float(a.o.c['Time Params']['updateListTime'])*60)/3600,2)} hours" ) a.o.time.sleep( tto - float(a.o.c['Time Params']['updateListTime']) * 60) #sleep until time to update print( f"Portfolio value of ${portVal} is less than minimum value of ${round(minPortVal,2)}" ) a.sellAll()
def algo12(): #TODO: fix sellAll instances so that it will only record in the event that we actually made trades f = open("algo12.txt", "r") #contains json info regarding trading j = a.json.loads(f.read()) f.close() symb = j['symb'] d = j["periodDateStart"].split("-") periodStartDate = date(int(d[0]), int(d[1]), int(d[2])) periodStartVal = float(j["periodPortStart"]) d = j["lastTradeDate"].split("-") lastTradeDate = date(int(d[0]), int(d[1]), int(d[2])) lastSellPrice = float(j["lastSellPrice"]) maxPrice = 0 # minPrice = 100000 #may be used later in trying to get the best buy currentPrice = 0 shares2buy = 0 buyPrice = 0 period = 10 #length of period (d) sellUp = 5 sellUpDn = 3 sellDn = 16 # buyDnUp = 1 portGain = 20 portLoss = 25 timeFromClose = 300 #seconds from close to start analyzing to buy timeSinceStart = 300 #seconds from start to analyze to sell (before infrequent checking) shortTime = 2 medTime = 20 longTime = 60 * 10 while True: #while the market is still alive print("\nMarket is alive") print("Today is " + str(date.today()) + ", the period start date is " + str(periodStartDate)) print("Day " + str(nwd(periodStartDate, date.today()) - 1) + " of " + str(period)) while (nwd(periodStartDate, date.today()) - 1 < period): #while within the period print("We're within the period.") [openTime, closeTime] = a.openCloseTimes(str( date.today())) #get the open and close times of today while (a.marketIsOpen() and date.today() > lastTradeDate): #while the market is open on a given day (that we haven't traded yet) print("\nMarket is open, and no trades made yet") print("Time is: " + str(a.dt.now())) if ( a.getShares(symb) > 0 ): #only check to sell if we have shares in the first place print("We have shares") buyPrice = a.getBuyPrice( symb) #set var to avoid lots of redundant calls while ((a.dt.now() - openTime).seconds < timeSinceStart): #while we're near the open time currentPrice = a.getPrice( symb) #set var to avoid lots of redundant calls print( str((a.dt.now() - openTime).seconds) + "s since open | stock change " + str(round((currentPrice / buyPrice - 1) * 100, 2)) + "%") #check frequently to sell if (currentPrice > buyPrice * (1 + sellUp / 100)): #if the stock price has reached the sell limit print("Stock has reached limit - up " + str( round(100 * (currentPrice / buyPrice - 1), 2) + "%")) maxPrice = max(maxPrice, currentPrice) if (currentPrice <= maxPrice * (1 - sellUpDn / 100)): print("Sell up conditions met.") if (a.sellAll(0)): #set trade flag lastTradeDate = date.today() lastSellPrice = currentPrice j['lastTradeDate'] = str(lastTradeDate) j['lastSellPrice'] = lastSellPrice time.sleep( shortTime) #we're excited, so check often else: time.sleep(medTime) #only check every so often if (lastTradeDate < date.today()): portVal = float(a.getAcct()['portfolio_value']) print("Checking portfolio status") if (portVal > periodStartVal * (1 + portGain / 100) or portVal < periodStartVal * (1 - portLoss / 100)): print("Portfolio won or lost - " + str(round(portVal / periodStartVal, 2)) + "%") if (a.sellAll(0)): periodStartDate = a.date.today() periodStartVal = portVal lastTradeDate = a.date.today() lastSellPrice = a.getPrice(symb) j['lastTradeDate'] = str(lastTradeDate) j['lastSellPrice'] = lastSellPrice j['periodStartDate'] = periodStartDate j['poeriodPortStart'] = periodStartVal #record the end of the period data portVal = float(a.getAcct()['portfolio_value']) print("Portfolio Value: $" + str(round(portVal, 2))) f = open("alpacaPortValues.txt", "a") f.write("\n" + str(date.today()) + "," + str(portVal)) f.close() print("Starting period over.") break else: print("Portfolio change: " + str( round((portVal / periodStartVal - 1) * 100, 2)) + "%") else: break if (lastTradeDate < date.today()): print("No trades made yet today.") while (a.timeTillClose() <= timeFromClose): #while we're close to the end of the day print("Close to closing | " + str(a.dt.now()) + " / " + str(closeTime)) #buy if no shares held, or sell if it reaches the sellUp % method currentPrice = a.getPrice(symb) maxPrice = 0 if (a.getShares(symb) == 0): print("No shares held. Buying.") #include buyDnUp & minPrice here shares2buy = int( float(a.getAcct()['buying_power']) / currentPrice) print( a.createOrder("buy", shares2buy, symb, "market", "day")) lastTradeDate = a.date.today() j['lastTradeDate'] = str(lastTradeDate) break elif (currentPrice >= a.getBuyPrice(symb) * (1 + sellUp / 100)): print("Shares still held, and price is going up") while (currentPrice >= maxPrice * (1 - sellUpDn) and a.timeTillClose() > shortTime * 2): print("Time left: " + str(a.timeTillClose( )) + "s | Stock change: " + str( round(currentPrice / a.getBuyPrice(symb), 2) - 1) + "%") currentPrice = a.getPrice(symb) maxPrice = max(maxPrice, currentPrice) time.sleep(shortTime) if ( currentPrice >= maxPrice * (1 - sellUpDn) ): #if the price is still up (hasn't started dropping yet), then wait till next morning to sell print( "Price is still up, but market is closing. Will continue tomorrow." ) else: if (a.sellAll(0)): lastTradeDate = a.date.today() lastSellPrice = currentPrice j['lastTradeDate'] = str(lastTradeDate) j['lastSellPrice'] = lastSellPrice break time.sleep(medTime) #if we're at any other time of the day #check slow - only sell if (lastTradeDate < a.date.today() and a.getShares(symb) > 0): if (a.getPrice(symb) >= a.getBuyPrice(symb) * (1 + sellUp / 100)): print("Price going up") maxPrice = 0 while (currentPrice >= maxPrice * (1 - sellUpDn / 100)): currentPrice = a.getPrice(symb) maxPrice = max(maxPrice, currentPrice) print("Current Price: " + str(currentPrice) + ", Max Price: " + str(maxPrice)) time.sleep(shortTime) if (a.sellAll(0)): lastSellPrice = currentPrice lastTradeDate = a.date.today() j['lastTradeDate'] = str(lastTradeDate) j['lastSellPrice'] = lastSellPrice break time.sleep( min(longTime, abs(a.timeTillClose() - timeFromClose)) ) #in case we're too close to the closing time, we don't want to overrun it else: break # set values and wait for the market to open again print("Done trading for the day.") f = open("algo12.txt", "w") f.write(a.json.dumps(j)) f.close() maxPrice = 0 currentPrice = 0 shares2buy = 0 print("Current Time: " + str(a.marketTime())) print("Will resume in " + str(a.timeTillOpen()) + " seconds") time.sleep(a.timeTillOpen()) #sell all at end of period and reset values print("End of period. Selling all and resetting.") if (a.sellAll(0)): #sell everything at the end of the period #record the end of the period data portVal = float(a.getAcct()['portfolio_value']) print("Portfolio Value: $" + str(round(portVal, 2))) f = open("alpacaPortValues.txt", "a") f.write("\n" + str(date.today()) + "," + str(portVal)) f.close() #record the trading info lastTradeDate = date.today() j['lastTradeDate'] = str(lastTradeDate) j['periodDateStart'] = str(date.today()) j['periodPortStart'] = a.getAcct()['portfolio_value'] maxPrice = 0 currentPrice = 0 shares2buy = 0 f = open("algo12.txt", "w") f.write(a.json.dumps(j)) f.close() print("Current Time: " + str(a.marketTime())) print("Will resume in " + str(a.timeTillOpen()) + " seconds") time.sleep(a.timeTillOpen()) '''