def algo3(): print("algo 3:\nrandomly buy/sell every x minutes") if (a.marketIsOpen()): num2Buy = 20 # of unique stocks to buy numShares = 10 # of shares of each stock to buy symbols = a.getVolatilePennies(5, 'up') pos = a.getPos() # symbols = a.getPennies(1,'up') min2wait = 5 if (int(a.marketTime()[4]) % min2wait == 0): if (random.randint(0, 1)): #buy from symbols list a.createOrder("buy", random.randint(1, numShares), symbols[random.randint(0, len(symbols) - 1)], "market", "day") else: #sell from positions list rndStk = pos[random.randint( 0, len(pos) - 1)] #get a random stock that's held a.createOrder("sell", random.randint(1, int(rndStk["qty"])), rndStk["symbol"], "market", "day")
def algo1(): print( "algo 1:\nbuy at market open\nif return >= X%, sell\nif return <= Y%, sell, rebuy a different stock\nsell at market close\nrepeat" ) if (a.marketIsOpen()): cashOnHand = float(a.getAcct()["cash"]) #avaiable cash to buy with maxPrice = 5 #should be 1,2, or 5 usually symbols = a.getVolatilePennies(maxPrice, 'up') uniqueAvailable = len(symbols) num2Buy = int( uniqueAvailable * 3 / 4 ) # of unique stocks to buy - don't do all of them, this should avoid too many repeats numShares = int(cashOnHand / maxPrice / num2Buy) # of shares of each stock to buy # symbols = a.getPennies(1,'up') min2hold = min( num2Buy, 5) #minnumber to go down to before selling all and restarting waitTime = 5 #time to wait (s) between checking again perc2sellup = 12 # sell at this % gain perc2selldn = 20 # sell at this % loss #TODO: add second perc to sell at based on some other factors (i.e. it hasn't changed much or something) while (timeTillClose() >= 300): #go until ~5 min before market closes pos = a.getPos() if (len(pos) >= min2hold): for e in pos: diff = float(e["current_price"]) - float( e["avg_entry_price"]) # print(e) perc = diff / float(e["avg_entry_price"]) * 100 if (diff > 0 or perc <= -3 / 4 * perc2selldn ): #show the info when it gets close to failing print(e["symbol"] + " - " + str(perc) + "%") if ((perc >= perc2sellup or perc <= -perc2selldn )): #if it meets the criteria to sell print( a.createOrder("sell", e["qty"], e["symbol"], "market", "day")) if (perc <= -perc2selldn ): #if it failed, rebuy a random stock a.buyRandom(1, symbols, numShares) else: a.sellAll(0) a.buyRandom(num2Buy, symbols, numShares) print("\n" + str(len(pos)) + " stocks remaining...\n") time.sleep(waitTime) a.sellAll(0) print("Market is Closed.")
def updateStockList(): global gainers, gainerDates, gStocksUpdated print("Updating stock list") #list of stocks that may gain in the near future as well as currently held stocks and their last gain date gainerDates = a.o.getGainers( list(dict.fromkeys(a.o.getList() + [e['symbol'] for e in a.getPos()])) ) #combine nasdaq list & my stocks & remove duplicates - order doesn't matter #only add gainers who are not in the news for a reverse stock split and have not already been traded today todaysTrades = a.getTrades(str(a.o.dt.date.today())) soldToday = [e['symbol'] for e in todaysTrades if e['side'] == 'sell'] for e in list(gainerDates): news = str(ns.scrape(e)).lower() #TODO: use the nasdaq calendar splits api instead of scraping the news if (not ("reverse stock split" in news or "reverse-stock-split" in news) and (e not in soldToday)): gainers.append(e) print(f"Done updating list - {len(gainers)} potential gainers") gStocksUpdated = True
def mark2sell(): p = a.getPos() splitters = a.o.reverseSplitters() for e in p: print(f"{e['symbol']}\tmarked to sell? ", end="") # news = str(ns.scrape(e['symbol'])).lower() # shouldSell = "reverse stock split" in news or "reverse-stock-split" in news or "bankrupt" in news #sell before a reverse stock split or bankruptcy shouldSell = e['symbol'] in splitters print(shouldSell) with open(a.o.c['File Locations']['latestTradesFile'], "r") as f: latestTrades = a.o.json.loads(f.read()) try: latestTrades['doubleJump'][e['symbol']]['shouldSell'] = shouldSell except Exception: #for legacy - transition from the old format latestTrades['doubleJump'][e['symbol']] = { 'shouldSell': shouldSell } with open(a.o.c['File Locations']['latestTradesFile'], "w") as f: f.write(a.o.json.dumps(latestTrades, indent=2))
def updateStockList(): global gainers, gStocksUpdated print("Updating stock list") gainers = {} #clear the gainer list #list of stocks that may gain in the near future as well as currently held stocks and their last gain date gainerDates = a.o.getGainers( list(dict.fromkeys(a.o.getList() + [e['symbol'] for e in a.getPos()])) ) #combine nasdaq list & my stocks & remove duplicates - order doesn't matter #only add gainers who are not slated for a reverse stock split and have not already been traded today todaysTrades = a.getTrades(str(a.o.dt.date.today())) soldToday = [e['symbol'] for e in todaysTrades if e['side'] == 'sell'] splitters = a.o.reverseSplitters() for e in gainerDates: # news = str(ns.scrape(e)).lower() # if(not ("reverse stock split" in news or "reverse-stock-split" in news) and (e not in soldToday)): if (e not in splitters and (e not in soldToday)): gainers[e] = gainerDates[e] #TODO: this could probably be reduced to remove gainerDates and just update gainers. removing the ones that show up in splitters rather than adding the ones not in splitters print(f"Done updating list - {len(gainers)} potential gainers") gStocksUpdated = True
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 algo11(): #initial conditions symb = 'xspa' #symbol to work with timeLimit = 10 #trading days since start to stop startDate = date(2020, 5, 6) #day first started investing startPortVal = float( a.getAcct()['portfolio_value']) #starting portfolio value #selling constants (%) portSellUp = 20 portSellDn = 25 stockSellDn = 16 stockSellUp = 2 stockSellUpDn = 1 #timing constants (s) countdown = 10 longwait = 60 * 10 shortWait = 30 #variables tradeMadeToday = False #flag if a trade has been made today currentPortVal = 0 currentStockVal = 0 sellPrice = 0 #price stocks sold at - $/share shares2buy = 0 #number of shares to buy in a given order #this assumes that shares are held of the stock 'symb', or no shares are held at all while (True): maxStockVal = 0 #additional variable to set/reset after the time limit/period #additional functionailty to choose new stocks on some cirteria should go here #at this point, all of the money should be in buying power #make sure that the shares are held in the correct stock, if not, prompt to sell if (a.getShares(symb) == 0 and not tradeMadeToday): if ( len(a.getPos()) ): #this shouldn't ever happen, but just in case, we error check print(str(a.getPos()).replace(',', '\n') + "\n") print("Error: Shares already held other than " + symb) if ( not a.sellAll(1) ): #prompt user to sell all - returns 0 if cancelled, 1 if finished selling sys.exit( "Only shares of '" + symb + "' are valid. Please sell all to proceed." ) #restart if cancelled - program probably won't work otherwise else: #this should happen the most often - if we're sure no stocks are held, then we can buy some if (not a.marketIsOpen() ): #wait until open, if it's not already print("Waiting till open to buy.") time.sleep(a.timeTillOpen()) shares2buy = int( float(acctInfo['buying_power']) / a.getPrice(symb)) print(a.createOrder("buy", shares2buy, symb, "market", "day")) tradeMadeToday = True startDate = date.today() #at this point, we should have as many shares as we can afford while (nwd(startDate, date.today()) <= timeLimit): #as long as we're in the time limit if (not tradeMadeToday and a.marketIsOpen()): currentStockVal = a.getPrice( symb) # if(a.getShares(symb)) else currentStockVal = 0 # if (currentStockVal < (a.getBuyPrice(symb) * (1 - stockSellDn / 100))): print("Lost the stock") a.sellAll(0) sellPrice = a.getPrice(symb) tradeMadeToday = True elif (currentStockVal >= (a.getBuyPrice(symb) * (1 + stockSellUp / 100)) and a.getBuyPrice(symb) > 0): print("Won the stock") while (currentStockVal > (maxStockVal * (1 - stockSellUpDn / 100))): time.sleep(shortwait) currentStockVal = a.getPrice(symb) maxStockVal = max(maxStockVal, currentStockVal) print("Current Stock Value: " + str(currentStockVal) + ", Sell price:" + str(maxStockVal * (1 - stockSellUpDn / 100))) a.sellAll(0) tradeMadeToday = True acctInfo = a.getAcct() currentPortVal = float(acctInfo['portfolio_value']) if (currentPortVal <= startPortVal * (1 - portSellDn / 100)): print("Lost the portfolio") a.sellAll(0) sellPrice = a.getPrice(symb) # tradeMadeToday = True break elif (currentPortVal >= startPortVal * (1 + portSellUp / 100)): print("Won the portfolio!") a.sellAll(0) sellPrice = a.getPrice(symb) # tradeMadeToday = True break if (not tradeMadeToday and a.getShares(symb) == 0): print("No trades today, and no shares held, so we're buying.") shares2buy = int( float(acctInfo['buying_power']) / a.getPrice(symb)) print(a.createOrder('buy', shares2buy, symb, 'market', 'day')) if (a.marketIsOpen() and not tradeMadeToday ): #this enforces 1 trade per day only during market open print( "Market is open, and no trades made today - Current Portfolio Value Change: " + str(a.getPortfolioChange(startPortVal)) + "%") time.sleep(longwait) else: print(str(timeTillOpen()) + " seconds till open. Be patient.") time.sleep(timeTillOpen() - countdown) tradeMadeToday = False #reset for the start of a new day for i in range(countdown, 0, -1): print(i) time.sleep(1) print("Welcome to day " + str(nwd(startDate, date.today())) + " of " + str(timeLimit) + " - Current Portfolio Value: " + a.getAcct()['portfolio_value'] + " | " + str(a.getPortfolioChange(startPortVal)) + "% from start of period.") print("End of Period. Selling all and starting over.") a.sellAll(0) tradeMadeToday = True startPortVal = float(a.getAcct()['portfolio_value']) startDate = date.today()
def algo8(): print( "algo 8:\nbuy a bunch of volatile stocks\nif stock return > portfolio return + some %, sell the stock, buy a new random one\nif portfolio return >= 2x target %, sellAll & stop for the day\nif portfolio return reached target %, but has since gone down, sellAll & stop for the day\nif portfolio return <= max allowed loss, then sellAll & stop for the day" ) openTime = int( a.marketTime() [3]) #this assumes the script is running before market is open startPortVal = a.getAcct()["last_equity"] maxPrice = 1 symbols = a.getVolatilePennies(maxPrice, 'up') percDiff = 2 #only sell if stock's return is this % higher than portfolio current gain/loss % targetPerc = 2 #shoot for this portfolio gain/day absMinPerc = 5 #biggest loss amount that we want at any point during the day (avoids major crashes) wait2start = 60 * 5 #wait this long (s) after open to start trading #wait for market to settle to start trading # while(a.marketTime()[3]<(openTime+wait2start)): # print("Market is open. Trading in "+str(round((wait2start-(a.marketTime()[3]-openTime))/60,2))+" minutes.") # time.sleep(60) if (a.marketIsOpen()): maxPrice = 1 #should be 1,2, or 5 usually symbols = a.getVolatilePennies(maxPrice, 'up') uniqueAvailable = len(symbols) num2Buy = int( uniqueAvailable * 3 / 4 ) # of unique stocks to buy - don't grab all from list, this should avoid too many repeats min2hold = 15 #minnumber to go down to before selling all and restarting waitTime = 5 #time to wait (s) between checking again perc2selldn = 20 # sell at this % loss targetPercMet = 0 # set flag if the target % has been met while (timeTillClose() >= 60): #go until ~1 min before market closes cashOnHand = float( a.getAcct()["cash"]) * 0.5 #avaiable cash to buy with numShares = int(cashOnHand / maxPrice / num2Buy) # of shares of each stock to buy pos = a.getPos() #get held positions portPerc = (float(a.getAcct()["equity"]) / float(startPortVal) - 1) * 100 #get % change of portfolio if (len(pos) >= min2hold): #as long as we have more than the minimum for e in pos: diff = float(e["current_price"]) - float( e["avg_entry_price"]) #check the gain/loss perc = diff / float( e["avg_entry_price"]) * 100 #get % change if (perc >= 3 / 4 * (portPerc + percDiff) or perc <= -3 / 4 * perc2selldn ): #show the info when it gets close to sell time print(e["symbol"] + " - " + str(round(perc, 2)) + "%") if ((perc >= (portPerc + percDiff) or perc <= -perc2selldn )): #if it meets the criteria to sell print( a.createOrder("sell", e["qty"], e["symbol"], "market", "day")) #sell that bitch a.buyRandom(1, symbols, numShares) #and buy a new random one else: #if we fall below minimum a.sellAll(0) #throw it all away a.buyFromTop(num2Buy, symbols, numShares) #and buy from the top again print("\n" + str(len(pos)) + " stocks held - Portfolio change: " + str(round(portPerc, 2)) + "% - " + str(timeTillClose()) + " seconds till close\n") if (portPerc >= 2 * targetPerc ): #if twice target % is reached, stop for the day a.sellAll() print("Target met x2! We done good. Done for the day.") break elif (portPerc >= targetPerc): #if target % is met, set the flag print("Target gain met! Seeing if we can go higher...") targetPercMet = 1 elif ( targetPercMet and portPerc < targetPerc ): #if the flag is set, but the portfolio % is now less, stop for the day a.sellAll() print( "We did well, but we done lost it. Done trading for the day." ) break elif ( portPerc <= -absMinPerc ): #if portfolio % is sucking balls, just give up for the day a.sellAll() print( "We lost it today. Calling it quits before too much is gone." ) break else: print("Market is closed.") print("Done trading for the day. See you tomorrow!")
def algo7(): print( "algo 7:\nbuy a bunch of volatile stocks\nif total portfolio value increased by X%, sell and hold there\nif total value decreased by Y%, sell aand hold there\nrepeat daily" ) #if it doesn't reach that by a certain time, then have secondary (and tertiary?) % to get to #if it's mostly negative by a certain time, then cut losses openTime = int( a.marketTime() [3]) #this assumes the script is running before market is open startPortVal = a.getAcct()["last_equity"] primaryPerc = 2 #sell everything if the porfolio reaches this gain time1 = openTime + 3600 * 2 #by this time (2hrs after open) secondaryPerc = primaryPerc / 2 #in case portfolio gain doesn't reach the primary percent time2 = openTime + int(3600 * 3.5) #by this time (3.5 hrs after open) tertiaryPerc = secondaryPerc / 2 time3 = openTime + 3600 * 4 #break even time downPerc = 1 #sell if the portfolio drops below this percent after a certain time timeDn = openTime + 3600 * 5 #currently not used - time2 is used in its place absMinPerc = 5 #biggest loss amount that we want at any point during the day wait2start = 60 * 15 #wait this long (s) after open to start trading #wait for market to settle to start trading # while(a.marketTime()[3]<(openTime+wait2start)): # print("Market is open. Trading in "+str(round((wait2start-(a.marketTime()[3]-openTime))/60,2))+" minutes.") # time.sleep(60) if (a.marketIsOpen()): cashOnHand = float(a.getAcct()["cash"]) #avaiable cash to buy with maxPrice = 1 #should be 1,2, or 5 usually symbols = a.getVolatilePennies(maxPrice, 'up') uniqueAvailable = len(symbols) num2Buy = int( uniqueAvailable * 3 / 4 ) # of unique stocks to buy - don't grab all from list, this should avoid too many repeats numShares = int(cashOnHand / maxPrice / num2Buy) # of shares of each stock to buy min2hold = min( num2Buy, 15) #minnumber to go down to before selling all and restarting waitTime = 5 #time to wait (s) between checking again perc2sellup = 12 # sell at this % gain perc2selldn = 20 # sell at this % loss while (timeTillClose() >= 60): #go until ~2 min before market closes pos = a.getPos() #get held positions if (len(pos) >= min2hold): #as long as we havee more than the minimum for e in pos: diff = float(e["current_price"]) - float( e["avg_entry_price"]) #check the gain/loss perc = diff / float( e["avg_entry_price"]) * 100 #get % change if (diff > 0 or perc <= -3 / 4 * perc2selldn ): #show the info when it gets close to failing print(e["symbol"] + " - " + str(round(perc, 2)) + "%") if ((perc >= perc2sellup or perc <= -perc2selldn )): #if it meets the criteria to sell print( a.createOrder("sell", e["qty"], e["symbol"], "market", "day")) #sell that bitch if (perc <= -perc2selldn ): #if it failed, rebuy a random stock a.buyRandom(1, symbols, numShares) else: #if we fall below minimum a.sellAll(0) #throw it all away a.buyFromTop(num2Buy, symbols, numShares) #and buy from the top again portPerc = (float(a.getAcct()["equity"]) / float(startPortVal) - 1) * 100 print("\n" + str(len(pos)) + " stocks held - Portfolio change: " + str(round(portPerc, 2)) + "% - " + str(timeTillClose()) + " seconds till close\n") if (portPerc >= primaryPerc): a.sellAll(0) print("Done trading for the day! We reached the mark.") break elif (portPerc >= secondaryPerc and int(a.marketTime()[3]) >= time1): a.sellAll(0) print("Done trading for the day! We got second best.") break elif (portPerc >= tertiaryPerc and int(a.marketTime()[3]) >= time2): a.sellAll(0) print( "Done trading for the day! We did okay, better than nothing." ) break elif (round(portPerc, 2) == 0 and int(a.marketTime()[3]) >= time3): a.sellAll(0) print("Done trading for the day! We broke even.") break elif ((portPerc <= -downPerc) and int(a.marketTime()[3]) >= timeDn): print() a.sellAll(0) print("Done trading for the day. We lost some today.") break elif (portPerc <= -absMinPerc): a.sellAll(0) print("Done trading for the day. We lost a fair amount today.") break time.sleep(waitTime) a.sellAll(0) print("Market is Closed.") '''