def BuyUpShortCrash(self): # SIm trades can only be 1 if len(self.prices) > self.lookback: if (self.currentPrice > self.prices[-self.lookback] * self.upfactor): amountToBuy = (self.balance - 10) / (self.currentPrice * (1 + self.fee)) fee = amountToBuy * self.currentPrice * self.fee if (self.balance >= fee + amountToBuy * self.currentPrice + 10): stoplossn = self.currentPrice * (1 - self.stoploss) self.balance -= (amountToBuy * self.currentPrice + fee) self.trades.append( BotTrade(self.functions, self.currentDate, amountToBuy, self.currentPrice, len(self.trades), stopLoss=stoplossn, fee=fee)) for trade in self.openTrades: if (self.currentPrice < self.prices[-self.lookback] * self.downfactor): self.balance += trade.volume * self.currentPrice self.trades[trade.id].close(self.currentDate, self.currentPrice, "In crash") else: self.handleStopLosses(trade)
def evaluatePositions(self, candlestick): openTrades = [] for trade in self.trades: if (trade.status == "OPEN"): openTrades.append(trade) # Make sure NoneType is handled if (self.movingAVG is None): self.movingAVG = 0 if (len(openTrades) < self.numSimulTrades): if (self.currentPrice < self.movingAVG): self.trades.append(BotTrade(self.currentPrice, stopLoss=.0001)) for trade in openTrades: if (self.currentPrice > self.movingAVG): trade.close(self.currentPrice) self.graph_data['date'].append(candlestick.date.astype(int)) self.graph_data['movingAverage'].append(self.movingAVG) self.graph_data['momentum'].append(self.momentum) self.graph_data['RSI'].append(self.RSI) df = pd.DataFrame(self.graph_data) df.to_csv( util.os.path.join( self.path, 'data/' + self.pair.replace('/', '-') + "/" + 'indicators.csv'))
def MACrossover(self): fifteenDayMA = self.indicators.movingAverage(self.prices, self.lowMA) fiftyDayMA = self.indicators.movingAverage(self.prices, self.highMA) if (fifteenDayMA > fiftyDayMA * self.mamultfactor): amountToBuy = (self.balance - 10) / (self.currentPrice * (1 + self.fee)) fee = amountToBuy * self.currentPrice * self.fee if (len(self.openTrades) < self.numSimulTrades and self.balance >= fee + amountToBuy * self.currentPrice + 10): stoplossn = self.currentPrice * (1 - self.stoploss) self.balance -= (amountToBuy * self.currentPrice + fee) self.trades.append( BotTrade(self.functions, self.currentDate, amountToBuy, self.currentPrice, len(self.trades), stopLoss=stoplossn, fee=fee)) for trade in self.openTrades: if (fifteenDayMA < fiftyDayMA / self.mamultfactor): self.balance += trade.volume * self.currentPrice self.trades[trade.id].close(self.currentDate, self.currentPrice, "MA Crossover") else: # self.handleStopLosses(trade) self.handleTrailingStop(trade)
def evaluatePositions(self, candlestick): # on ne gere que un seul trade openTrades = [] for trade in self.trades: if (trade.status == "OPEN"): openTrades.append(trade) if (len(openTrades) < self.numSimulTrades): if self.conditionOpen(): self.trades.append( BotTrade(self.currentPrice, candlestick.startTime, self.stopLoss)) try: if self.backtest == False: if self.short_mode: self.output.sendNotif( "SELL", "Signal Short | Price: " + str(self.currentPrice) + ' | Period: ' + str(self.period)) else: self.output.sendNotif( "BUY", "Signal Long | Price: " + str(self.currentPrice) + ' | Period: ' + str(self.period)) except Exception as e: print e for trade in openTrades: if self.conditionClose(trade): print("vendu par target: " + str(self.currentPrice)) trade.close(self.currentPrice, candlestick.startTime)
def evaluatePositions(self): prices = [] over_last_n_periods = 15 lastCandlestick = self.candlesticks[-1] for i in range(1, over_last_n_periods + 1): prices.append(self.candlesticks[-i].priceAverage) if (self.trades and self.trades[-1].status == "CLOSED") or not self.trades: # buy if lastCandlestick.priceAverage < self.indicators.movingAverage( prices): currentTrade = BotTrade(self.trades.__len__() + 1, lastCandlestick.close, lastCandlestick.date, self.currentBal) self.trades.append(currentTrade) # currentTrade.logBuy() if self.trades and self.trades[-1].status == "OPEN": lastTrade = self.trades[-1] # sell if lastCandlestick.priceAverage > self.indicators.movingAverage( prices): lastTrade.close(lastCandlestick.close, lastCandlestick.date) # lastTrade.logSell() self.currentBal = lastTrade.currentBal
def BuyLowSellHigh(self): rsi = self.indicators.RSI(self.prices, self.rsiperiod) if (rsi < self.lowrsi): amountToBuy = (self.balance - 10) / (self.currentPrice * (1 + self.fee)) fee = amountToBuy * self.currentPrice * self.fee if (len(self.openTrades) < self.numSimulTrades and self.balance >= fee + amountToBuy * self.currentPrice + 10): stoplossn = self.currentPrice * (1 - self.stoploss) self.balance -= (amountToBuy * self.currentPrice + fee) self.trades.append( BotTrade(self.functions, self.currentDate, amountToBuy, self.currentPrice, len(self.trades), stopLoss=stoplossn, fee=fee)) for trade in self.openTrades: if (rsi > self.highrsi): self.balance += trade.volume * self.currentPrice self.trades[trade.id].close(self.currentDate, self.currentPrice, "Overbought RSI") else: self.handleStopLosses(trade)
def getAllOpenTrades(self): conn = self.connection() cur = conn.cursor() cur.execute("SELECT * FROM trades where close_date is NULL") cur.close() conn.close() output = [] for r in cur: trade = BotTrade(self.parent, 0, 0 if r[3] is None else float(r[3]), 0 if r[1] is None else float(r[1]), 0, 0, float(r[6]), 0, 1) trade.externalId = r[0] output.append(trade) return output
def movingaverage(self, MAlong, MAshort, count): if self.currentBTC == None: self.coinVolume = 1 else: buy_volume = self.USDpertrade/self.currentBTC self.coinVolume = buy_volume/self.currentPrice self.coinVolume = 1 newOpenedTrades = 0 newClosedTrades = 0 openTrades = [] for trade in self.trades: if trade.status == 'OPEN': openTrades.append(trade) self.MAlong.append(self.indicators.SMA(self.prices,MAlong)) self.MAshort.append(self.indicators.SMA(self.prices,MAshort)) if self.MAlong[-1]==None: pass else: if self.print: print('Price:',self.currentPrice,'\tMAlong:',self.MAlong[-1], 'MAshort:',self.MAshort[-1]) if count > MAlong: if ((self.MAshort[-1])>self.MAlong[-1]): if len(openTrades)<self.numSimul: #need to embed the trade volume into the trade object, otherwise we sell more volume than be buy. self.trades.append(BotTrade(self.currentPrice,self.coinVolume, self.print)) newOpenedTrades+=1 self.balance -= self.coinVolume*self.trades[-1].entryPrice for trade in openTrades: if self.MAshort[-1]<self.MAlong[-1]:# or (self.data[count]/trade.entryPrice)>1.05 or (self.data[count]/trade.entryPrice)<0.95: newClosedTrades+=1 if count == self.length: trade.close(self.currentPrice) else: trade.close(self.currentPrice) self.profit+=trade.profit() self.balance+=trade.volume*trade.exitPrice self.balanceList.append(self.balance) if newClosedTrades>0: self.selllist.append(True) else: self.selllist.append(False) if newOpenedTrades>0: self.buylist.append(True) else: self.buylist.append(False)
def main(argv): #chart = BotChart("poloniex", "BTC_ETH", 300) chart = BotChart("poloniex", "BTC_XMR", 300) #chart = BotChart("poloniex", "BTC_DASH", 300) strategy = BotStrategy() for candlestick in chart.getPoints(): #print(candlestick) strategy.tick(candlestick) BotTrade.export() series = read_csv('export.csv', parse_dates=[0], index_col=0, squeeze=True, date_parser=parser) series.plot() pyplot.show()
def buy(self, rate, total, date, stopLoss=0, takeProfit=0): amount = total / rate order = BotTrade('BUY', rate=rate, amount=amount, total=total, date=date, stopLoss=stopLoss, takeProfit=takeProfit, backtest=self.backTest, forwardtest=self.forwardTest) self.trades.append(order)
def evaluatePositions(self): openTrades = [] for trade in self.trades: if (trade.status == "OPEN"): openTrades.append(trade) if (len(openTrades) < self.numSimulTrades): if (self.currentPrice < self.indicators.movingAverage(self.prices,15)): self.trades.append(BotTrade(self.currentPrice,stopLoss=.0001)) elif(self.indicators.RSI(self.prices,15) <= self.minRSI): self.trades.append(BotTrade(self.currentPrice,stopLoss=.0001)) elif(self.indicators.momentum(self.prices,15) >= self.minMomentum): self.trades.append(BotTrade(self.currentPrice,stopLoss=.0001)) for trade in openTrades: if (self.currentPrice > self.indicators.movingAverage(self.prices,15)): trade.close(self.currentPrice) elif(self.indicators.RSI(self.prices,15) >= self.maxRSI): trade.close(self.currentPrice) elif(self.indicators.momentum(self.prices,15) <= self.maxMomentum): trade.close(self.currentPrice)
def sell(self, rate, amount, date, stopLoss=0, takeProfit=0): total = rate * amount order = BotTrade('SELL', rate=rate, amount=amount, total=total, date=date, stopLoss=stopLoss, takeProfit=takeProfit, backtest=self.backTest, forwardtest=self.forwardTest) self.trades.append(order)
def macd(self, slow, fast, signal, count, lengthPrices): if self.currentBTC == None: self.coinVolume = self.USDpertrade/self.currentPrice else: buy_volume = self.USDpertrade/self.currentBTC self.coinVolume = buy_volume/self.currentPrice newOpenedTrades = 0 newClosedTrades = 0 openTrades = [] for trade in self.trades: if trade.status == 'OPEN': openTrades.append(trade) if len(self.prices)>slow: self.previousEMAslow = self.indicators.EMA(self.prices, slow, self.previousEMAslow) self.previousEMAfast = self.indicators.EMA(self.prices, fast, self.previousEMAfast) self.EMAfast.append(self.previousEMAfast) self.EMAslow.append(self.previousEMAslow) self.MACD.append(self.EMAfast[-1]-self.EMAslow[-1]) self.previousEMAmacd = self.indicators.EMA(self.MACD, signal, self.previousEMAmacd) self.signal.append(self.previousEMAmacd) if len(self.prices)>100: self.difference(self.signal[-1]-self.MACD[-1]) if (self.MACD[-1]>(self.signal[-1]+self.maxDiff/4)) and (self.MACD[-2]>self.signal[-2]): if len(openTrades)<self.numSimul: self.trades.append(BotTrade(self.currentPrice,self.coinVolume, self.print)) newOpenedTrades+=1 self.balance -= self.coinVolume*self.currentPrice self.numtrades+=1 for trade in openTrades: if ((self.MACD[-1]<self.signal[-1]) and (self.MACD[-2]>self.signal[-2])) or count == lengthPrices-1: trade.close(self.currentPrice) self.balance+=trade.volume*self.currentPrice self.profit+=trade.profit() newClosedTrades+=1 #graphing section self.balanceList.append(self.balance) if newClosedTrades>0: self.selllist.append(True) else: self.selllist.append(False) if newOpenedTrades>0: self.buylist.append(True) else: self.buylist.append(False)
def evaluate_positions(self): openTrades = [] for trade in self.trades: if trade.status == "OPEN": openTrades.append(trade) # Instantiate indicator. slowk, slowd = self.indicators.STOCH(self.highs, self.lows, self.closes) # Only open a trade when the number of open trades is not more than the configured max allowed. # And there is enough data for indicator if len(openTrades) < self.num_simultaneous_trades and len( self.prices) > self.stoch_period: ######################### # Entry Strategy ######################### # Buy/Long if slowk[-1] <= self.over_sold: self.output.log("{} buy signal".format(self._NAME)) self.trades.append( BotTrade(pair=self.pair, current_price=self.currentPrice, trade_type="BUY", order_type='market', stop_loss_percent=self.stoch_stop_loss)) # NOTE: LEVERAGE REQUIRED FOR SELLING ON KRAKEN ############### # Exit Strategy ############### for trade in openTrades: # Buy/Long if self.TAKE_PROFIT: # Exit on % profit. if self.currentPrice >= ( trade.entry_price * (1.0 + self.take_profit) ) and trade.trade_type.upper() == "BUY": self.output.log("{} Closed on {}% gain".format( self._NAME, self.take_profit * 100)) trade.close(self.currentPrice) continue if self.OVER_BOUGHT: # Exit on overbought signal. if slowk[-1] >= self.over_bought and trade.trade_type.upper( ) == "BUY": self.output.log("{} Closed on over bought signal".format( self._NAME)) trade.close(self.currentPrice) continue
def evaluatePositions(self): openTrades = [] for trade in self.trades: if (trade.status == "OPEN"): openTrades.append(trade) if (len(openTrades) < self.numSimulTrades): if (self.currentPrice < self.indicators.movingAverage( self.prices, 20)): self.trades.append(BotTrade(self.currentPrice, stopLoss=.0001)) for trade in openTrades: if (self.currentPrice > self.indicators.movingAverage( self.prices, 20)): trade.close(self.currentPrice)
def openShort(self, amt): fee = amt * self.currentPrice * self.fee if (self.balance >= fee + amt * self.currentPrice + 10) and ( fee + amt * self.currentPrice + 10) > self.origBalance * 0.02: stoplossn = self.currentPrice * (1 + self.stoploss) self.balance += (amt * self.currentPrice - fee) self.trades.append((BotTrade(self.functions, self.currentDateOrig, -1 * amt, self.currentPrice, len(self.trades), stopLoss=stoplossn, fee=fee, expiry=self.advance, log=self.trial)))
def evaluate_positions(self): openTrades = [] for trade in self.trades: if trade.status == "OPEN": openTrades.append(trade) # Instantiate indicator. _, _, hist = self.indicators.MACD(self.prices, self.macd_slow, self.macd_fast, self.macd_signal) # Only open a trade when the number of open trades is not more than the configured max allowed. # And there is enough data for indicator if len(openTrades) < self.num_simultaneous_trades and len( self.prices) > self.hist_period: ######################### # Entry Strategy ######################### # Buy/Long if self.MACD_CROSSOVER: if hist[-2] < 0.0 < hist[-1]: self.output.log("{} buy signal. MACD crossover".format( self._NAME)) self.trades.append( BotTrade(pair=self.pair, current_price=self.current_price, trade_type="BUY", order_type='market', stop_loss_percent=self.stop_loss_percent)) # NOTE: LEVERAGE REQUIRED FOR SELLING ON KRAKEN ############### # Exit Strategy ############### for trade in openTrades: # Buy/Long if self.TAKE_PROFIT: # Exit on % profit. if self.current_price >= ( trade.entry_price * (1.0 + self.take_profit) ) and trade.trade_type.upper() == "BUY": self.output.log("{} Closed on {}% gain".format( self._NAME, self.take_profit * 100)) trade.close(self.current_price) continue
def evaluatePositions(self): currentTime= datetime.datetime.now() openTrades = [] for trade in self.trades: if (trade.status == "OPEN"): openTrades.append(trade) if (len(openTrades) < self.numSimulTrades): if ((self.strategyTradingMetric-self.currentPrice)> self.entryEdge): btrade= BotTrade(self.currentPrice, stopLossEdge=self.stopLossEdge) self.trades.append(btrade) self.updateExecutions(trade=btrade, executionTime=btrade.entryTime, executionPrice=btrade.entryPrice) for trade in openTrades: if (self.currentPrice > self.strategyTradingMetric): if (currentTime-trade.entryTime).seconds>self.timePosEdge: trade.close(self.currentPrice) self.updateExecutions(trade=trade, executionTime=trade.exitTime, executionPrice=trade.exitPrice) self.updateTrades(trade=trade) self.lastTradePnl= trade.pnl self.totalPnl= self.totalPnl+self.lastTradePnl
def MACrossover(self, lowMA, highMA): fifteenDayMA = self.indicators.movingAverage(self.prices,self.lowMA) fiftyDayMA = self.indicators.movingAverage(self.prices,self.highMA) # print(fifteenDayMA, fiftyDayMA) if (len(self.openTrades) < self.numSimulTrades): if (fifteenDayMA > fiftyDayMA * self.mamultfactor ): amountToBuy = self.balance * 0.2 / self.currentPrice fee = amountToBuy * self.currentPrice * self.fee stoploss = self.currentPrice * 0.1 self.currentId += 1 self.balance -= (amountToBuy * self.currentPrice + fee) self.trades.append(BotTrade(self.functions, self.currentDate, amountToBuy, self.currentPrice,self.currentId,stopLoss=stoploss, fee=fee)) for trade in self.openTrades: if (fifteenDayMA < fiftyDayMA / self.mamultfactor): self.balance += trade.volume * self.currentPrice trade.close(self.currentDate, self.currentPrice, "MA Crossover") elif (trade.stopLoss): if (trade.entryPrice - self.currentPrice > trade.stopLoss): trade.close(self.currentDate, self.currentPrice, "Stoploss") self.balance += trade.volume * self.currentPrice
def evaluatePositions(self, candlestic): openTrades = [] self.SMA1 = self.indicators.movingAverage(self.prices, self.vars.movingAvPeriod, self.currentPrice) self.SMA2 = self.indicators.movingAverage(self.prices, self.vars.movingAvPeriod2, self.currentPrice) self.EMA1 = self.indicators.EMA(self.prices, self.vars.movingAvPeriod, self.currentPrice) self.EMA2 = self.indicators.EMA(self.prices, self.vars.movingAvPeriod2, self.currentPrice) self.RSI = self.indicators.RSI(self.prices) self.BollUp = self.indicators.BollUp(self.prices, self.vars.BollPeriod, self.currentPrice) self.BollDown = self.indicators.BollDown(self.prices, self.vars.BollPeriod, self.currentPrice) for trade in self.trades: if (trade.status == "OPEN"): openTrades.append(trade) if (len(openTrades) < self.numSimulTrades): #--------------------------------------------------------------# #------Part 1.3.A: Adding a trade if the conditions are met----# #--------------------------------------------------------------# if self.strategy1(True): #self.output.log("Trade Opened. Currentprice: "+str(self.currentPrice)+", MovAverage: "+str(self.indicators.movingAverage(self.prices,self.vars.movingAvPeriod,self.currentPrice))) candlestic.label = "'Buy'" self.trades.append( BotTrade(self.currentTime, self.currentPrice)) self.numOfTrades += 1 for trade in openTrades: if self.strategy1(False): #self.output.log("Trade Closed. Currentprice: "+str(self.currentPrice)+", MovAverage: "+str(self.indicators.movingAverage(self.prices,self.vars.movingAvPeriod,self.currentPrice))) candlestic.label = "'Sell'" trade.close(self.currentPrice, self.currentTime)
import sys sys.path.append("Connections") sys.path.append("Models") from mysql_database import BotFunctions from bottrade import BotTrade from datetime import datetime import mysql_database hey = mysql_database.BotFunctions() trade = BotTrade(1, datetime.now(), 5, 645, 2, 0.1, 10, 20) trade.externalId = hey.createTrade(trade) trade.close(datetime.now(), 700, 'reason') hey.closeTrade(trade) print(hey.getTradeById(trade.externalId))
def evaluatePositions(self): openTrades = [] for trade in self.trades: if (trade.status == "OPEN"): openTrades.append(trade) if len(openTrades) < self.numTrades and self.holdingsUSD > self.tradeAmount: if self.mode in ["MACD", "ALL"] and self.MACDDiff[-1] < self.MACDSignal[-1] and self.MACDDiff[-2] > self.MACDSignal[-2]: self.trades.append(BotTrade(self.date, "MACD", self.pair, self.currentPrice, self.tradeAmount, self.stopLoss, self.targetPrice, self.backtest, self.output)) self.updateBalance(self.tradeAmount / self.currentPrice, self.currentPrice) self.action.append('Open MACD=, Amount=' + str(self.tradeAmount) + ', Price=' + str(self.currentPrice)) elif self.mode in ["MACD2", "ALL"] and self.MACDDiff[-1] < 500 and ((self.MACDDiff[-1] > 0 and self.MACDDiff[-2] < 0) or (self.MACDDiff[-1] < self.MACDSignal[-1] and self.MACDDiff[-2] > self.MACDSignal[-2])): self.trades.append(BotTrade(self.date, "MACD2", self.pair, self.currentPrice, self.tradeAmount, self.stopLoss, self.targetPrice, self.backtest, self.output)) self.updateBalance(self.tradeAmount / self.currentPrice, self.currentPrice) self.action.append('Open MACD2=, Amount=' + str(self.tradeAmount) + ', Price=' + str(self.currentPrice)) elif self.mode in ["MACD3", "ALL"] and self.MACDDiff[-1] > 0 and self.MACDDiff[-2] < 0: self.trades.append(BotTrade(self.date, "MACD3", self.pair, self.currentPrice, self.tradeAmount, self.stopLoss, self.targetPrice, self.backtest, self.output)) self.updateBalance(self.tradeAmount / self.currentPrice, self.currentPrice) self.action.append('Open MACD3=, Amount=' + str(self.tradeAmount) + ', Price=' + str(self.currentPrice)) elif self.mode in ["BBAND", "ALL"] and self.prices[-1] > self.lowerBBand[-1] and self.prices[-2] < self.lowerBBand[-2]: self.trades.append(BotTrade(self.date, "BBAND", self.pair, self.currentPrice, self.tradeAmount, self.stopLoss, self.targetPrice, self.backtest, self.output)) self.updateBalance(self.tradeAmount / self.currentPrice, self.currentPrice) self.action.append('Open BBAND, Amount='+ str(self.tradeAmount) + ', Price=' + str(self.currentPrice)) elif self.mode in ["RSI"] and self.rsi[-1] < 30 and self.rsi[-2] > 30: self.trades.append(BotTrade(self.date, "RSI", self.pair, self.currentPrice, self.tradeAmount, self.stopLoss, self.targetPrice, self.backtest, self.output)) self.updateBalance(self.tradeAmount / self.currentPrice, self.currentPrice) self.action.append('Open RSI, Amount='+ str(self.tradeAmount) + ', Price=' + str(self.currentPrice)) elif len(self.prices) > 12: if self.mode in ["DROP", "ALL"] and self.prices[-1] < self.prices[-6] *.95 and self.prices[-1] > self.prices[-2]: self.trades.append(BotTrade(self.date, "DROP", self.pair, self.currentPrice, self.tradeAmount, self.stopLoss, self.targetPrice, self.backtest, self.output)) self.updateBalance(self.tradeAmount / self.currentPrice, self.currentPrice) self.action.append('Open DROP, Amount='+ str(self.tradeAmount) + ', Price=' + str(self.currentPrice)) for trade in openTrades: if (self.currentPrice < trade.stopLoss): trade.close(self.date, self.currentPrice, "STOPLOSS") self.updateBalance(-trade.quantity, self.currentPrice) self.action.append('Close STOPLOSS=' + str(self.currentPrice)) elif trade.type in ["MACD"] and ((self.MACDDiff[-2] > 0 and self.MACDDiff[-1] < 0) or (self.MACDDiff[-1] > self.MACDSignal[-1] and self.MACDDiff[-2] < self.MACDSignal[-2])) and self.currentPrice > trade.targetPrice: trade.close(self.date, self.currentPrice, "MACD") self.updateBalance(-trade.quantity, self.currentPrice) self.action.append('CLOSE MACD=' + str(self.currentPrice)) elif trade.type in ["MACD2"] and self.MACDDiff[-1] > self.MACDSignal[-1] and self.MACDDiff[-2] < self.MACDSignal[-2] and self.currentPrice > trade.targetPrice: trade.close(self.date, self.currentPrice, "MACD2") self.updateBalance(-trade.quantity, self.currentPrice) self.action.append('CLOSE MACD2=' + str(self.currentPrice)) elif trade.type in ["MACD3"] and self.MACDDiff[-2] > 0 and self.MACDDiff[-1] < 0 and self.currentPrice > trade.targetPrice: trade.close(self.date, self.currentPrice, "MACD3") self.updateBalance(-trade.quantity, self.currentPrice) self.action.append('CLOSE MACD3=' + str(self.currentPrice)) elif trade.type in ["BBAND"] and self.prices[-1] < self.upperBBand[-1] and self.prices[-2] > self.upperBBand[-2] and self.currentPrice > trade.targetPrice: trade.close(self.date, self.currentPrice, "BBAND") self.updateBalance(-trade.quantity, self.currentPrice) self.action.append('CLOSE BBAND=' + str(self.currentPrice)) elif trade.type in ["RSI"] and self.rsi[-1] > 65 and self.rsi[-2] < 65 and self.currentPrice > trade.targetPrice: trade.close(self.date, self.currentPrice, "RSI") self.updateBalance(-trade.quantity, self.currentPrice) self.action.append('CLOSE RSI=' + str(self.currentPrice)) """elif trade.type in ["DROP"] and self.currentPrice > trade.targetPrice: trade.close(self.date, self.currentPrice, "DROP") self.updateBalance(-trade.quantity, self.currentPrice) self.action.append('CLOSE DROP=' + str(self.currentPrice))""" self.tradeAmount = int((self.holdingsUSD - 1) / self.numTrades)
def evaluatePositions(self): MacdCurrent = None MacdPrevious = None SignalCurrent = None SignalPrevious = None openTrades = [] for trade in self.trades: if (trade.status == "OPEN"): openTrades.append(trade) if (len(openTrades) < self.numSimulTrades): #if (self.currentPrice < self.indicators.movingAverage(self.prices,15)): #if (float(ticker['BTC_ZEC']['percentChange']) < 0): #print("Momentum: " + str(self.indicators.momentum(self.closes))) #print("Pivot: " + str(self.indicators.Pivot('BTC_ZEC', 300,self.date))) # dont need to calculate this every tick #print("RSI : " + str(self.indicators.RSI(self.prices))) #slow, fast, signal = self.indicators.MACD(self.closes) #print(slow) #print(fast) #print(signal) if ( len(self.closes) > 26 + 2 ): # Need to have enought prices in order to calculate the slowEMA SlowEMA = (self.indicators.EMA(self.closes, 26)) FastEMA = (self.indicators.EMA(self.closes, 12)) self.MACD_History.append( self.indicators.iMACD(SlowEMA, FastEMA)) MacdCurrent = self.MACD_History[ -1] # this is the most recent MACD in the list if (len(self.MACD_History) > 2): MacdPrevious = ( self.MACD_History[-2] ) # This is the second most recent MACD in the List if (len(self.MACD_History) > 9 + 2): SignalCurrent = self.indicators.EMA(self.MACD_History, 9) self.MACD_Signal_History.append(SignalCurrent) if (len(self.MACD_Signal_History) > 2): SignalPrevious = self.MACD_Signal_History[-2] #print("MACD: ") #print(MacdCurrent) #print(MacdPrevious) #print(SignalCurrent) #print(SignalPrevious) if (len(self.closes) > 100): if (MacdCurrent and MacdPrevious and SignalCurrent and SignalPrevious): if (MacdCurrent < 0 and MacdCurrent > SignalCurrent and MacdPrevious < SignalPrevious and self.indicators.RSI(self.prices, 14) < 50): self.trades.append( BotTrade(self.currentPrice, stopLoss=self.stopLoss)) #if (self.indicators.trend(self.prices,self.trendPeriod) == 1 and self.currentVolume > self.minVolume): #self.trades.append(BotTrade(self.currentPrice,stopLoss=self.stopLoss)) #if (self.indicators.RSI(self.prices,14) < 30 and self.currentVolume > self.minVolume): # self.trades.append(BotTrade(self.currentPrice,stopLoss=self.stopLoss)) #print bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC for trade in openTrades: currentProfit = float(self.currentPrice) - float(trade.entryPrice) if currentProfit > 0: print("entry: " + str(trade.entryPrice)) print(bcolors.OKGREEN + str(currentProfit) + bcolors.ENDC) else: print("entry: " + str(trade.entryPrice)) print(bcolors.WARNING + str(currentProfit) + bcolors.ENDC) #if (MacdCurrent and MacdPrevious and SignalCurrent and SignalPrevious): # if (MacdCurrent > 0 and MacdCurrent < SignalCurrent and MacdPrevious > SignalPrevious): if (self.currentPrice >= (float(trade.entryPrice) + self.takeProfit) or self.date > 1499309550 - 300): trade.close(self.currentPrice)
def main(argv): trader = BotTrade("BTC-XMR")
def evaluate_positions(self): openTrades = [] for trade in self.trades: if trade.status == "OPEN": openTrades.append(trade) # Instantiate indicator. slowk, slowd = self.indicators.STOCH(self.highs, self.lows, self.closes, fastk_period=self.stoch_period) # Only open a trade when the number of open trades is not more than the configured max allowed. # And there is enough data for indicator if len(openTrades) < self.num_simultaneous_trades and len(self.prices) > self.hist_period: ######################### # Entry Strategy ######################### # Buy/Long if self.PRICE_ABOVE_MA: if self.moving_avgs[-1] < self.current_price and self.stoch_ready_to_buy and not self.cool_down_period: self.output.log("{} buy signal. Ready to buy: {} & typical price {} above MA".format(self._NAME, self.stoch_ready_to_buy, self.current_price - self.moving_avgs[-1])) self.trades.append(BotTrade(pair=self.pair, current_price=self.current_price, trade_type="BUY", order_type='market', stop_loss_percent=self.stoch_stop_loss)) self.cool_down_period = 5 # Wait n periods until another trade can be made if self.STOCH_OS: # Stochastic %K crossover %D below midline (50) if slowk[-1] < self.mid_line and slowd[-1] < self.mid_line and slowk[-2] < slowd[-2] and slowk[-1] > slowd[-1]: self.output.log("{} buy signal. Stochastic %K crossover %D below midline(50)".format(self._NAME, self.stoch_ready_to_buy, self.current_price - self.moving_avgs[-1])) self.trades.append(BotTrade(pair=self.pair, current_price=self.current_price, trade_type="BUY", order_type='market', stop_loss_percent=self.stoch_stop_loss)) # NOTE: LEVERAGE REQUIRED FOR SELLING ON KRAKEN ############### # Exit Strategy ############### for trade in openTrades: # Buy/Long if self.PRICE_BELOW_MA: # Exit when price is below moving average for two consecutive candles, indicating a downward price trend if self.current_price < self.moving_avgs[-1] and self.current_price < self.moving_avgs[-2]: self.output.log("{} Closed on Price {} below MA for two candles".format(self._NAME, self.moving_avgs[-1] - self.current_price)) trade.close(self.current_price) continue if self.MA_SLOPE_SLOWING and len(self.slope_difference) > 6: # Exit when the rate of the SLOPE of the n-period MA begins to slow. if self.slope_difference[-1] < self.slope_difference[-2] < self.slope_difference[-3] < \ self.slope_difference[-4] < self.slope_difference[-5] < self.slope_difference[-6] < \ self.slope_difference[-7] < self.slope_difference[-8]: self.output.log("{} Closed on slope slowing. Slope went down by {}, {}, {}, {}".format( self._NAME, self.slope_difference[-4], self.slope_difference[-3], self.slope_difference[-2], self.slope_difference[-1])) trade.close(self.current_price) continue if self.TAKE_PROFIT: # Exit on % profit. if self.current_price >= (trade.entry_price * (1.0 + self.take_profit)) and trade.trade_type.upper() == "BUY": self.output.log("{} Closed on {}% gain".format(self._NAME, self.take_profit * 100)) trade.close(self.current_price) continue if self.OVER_BOUGHT: # Exit on overbought signal. if slowk[-1] >= self.over_bought and trade.trade_type.upper() == "BUY": self.output.log("{} Closed on over bought signal".format(self._NAME)) trade.close(self.current_price) continue
def main(argv): trader = BotTrade("BTC-BAT", 0.001) trader.simpleEMAtrade(10, 'fiveMin')
def evaluatePositions(self): openTrades = [] for trade in self.trades: if (trade.status == "OPEN"): openTrades.append(trade) if (len(openTrades) < self.numSimulTrades): if (self.btc_historical_total <= 100000): bitcoin_query = 'BTC OR Bitcoin OR $BTC' btc_historical_tweets, self.btc_sinceid = tweets.get_tweets( 50, self.btc_sinceID, bitcoin_query) btc_total_score, btc_positive, btc_negative, btc_total = tweets.classify( btc_historical_tweets) self.btc_historical_positive = self.btc_historical_positive + btc_positive self.btc_historical_negative = self.btc_historical_negative + btc_negative self.btc_historical_score = self.btc_historical_score + btc_total_score self.btc_historical_total = self.btc_historical_total + btc_total self.btc_historical_percent = (self.btc_historical_positive / self.btc_historical_total) * 100 ethereum_query = 'Ethereum OR ETH OR $ETH' eth_historical_tweets, self.eth_sinceID = tweets.get_tweets( 50, self.eth_sinceID, ethereum_query) eth_total_score, eth_positive, eth_negative, eth_total = tweets.classify( eth_historical_tweets) self.eth_historical_positive = self.eth_historical_positive + eth_positive self.eth_historical_negative = self.eth_historical_negative + eth_negative self.eth_historical_score = self.eth_historical_score + eth_total_score self.eth_historical_total = self.eth_historical_total + eth_total self.eth_historical_percent = (self.eth_historical_positive / self.eth_historical_total) * 100 if self.btc_historical_total >= 100000: print '\033[1m' + "Historical Tweets Analyzed" print "historical btc percent: " + str( self.btc_historical_percent) print "historical eth percent: " + str( self.eth_historical_percent) print '\033[0m' elif (self.btc_historical_total > 100000): bitcoin_query = 'BTC OR Bitcoin OR $BTC' btc_tweets, sinceid_recent = tweets.get_tweets( 50, 0, bitcoin_query) btc_total_score2, btc_positive2, btc_negative2, btc_total2 = tweets.classify( btc_tweets) btc_percent = (btc_positive2 / btc_total2) * 100 ethereum_query = 'Ethereum OR ETH OR $ETH' eth_tweets, sinceid_recent = tweets.get_tweets( 50, 0, ethereum_query) eth_total_score2, eth_positive2, eth_negative2, eth_total2 = tweets.classify( eth_tweets) eth_percent = (eth_positive2 / eth_total2) * 100 if (eth_percent > 1.042 * self.eth_historical_percent or btc_percent < 0.943 * self.btc_historical_percent): if btc_percent < 0.943 * self.btc_historical_percent: self.btc_sentiments = [] self.btc_trading_percent = btc_percent self.type_of_trade = 'BTC' self.trades.append(BotTrade(self.prices, stopLoss=0.01)) elif (eth_percent > 1.042 * self.eth_historical_percent): self.eth_sentiments = [] self.eth_trading_percent = eth_percent self.type_of_trade = 'ETH' self.trades.append(BotTrade(self.prices, stopLoss=0.01)) else: self.type_of_trade = '' time.sleep(60 * 5) for trade in openTrades: if (self.type_of_trade == 'BTC'): bitcoin_query = 'BTC OR Bitcoin OR $BTC' btc_tweets, sinceid_recent = tweets.get_tweets( 10, 0, bitcoin_query) btc_total_score2, btc_positive2, btc_negative2, btc_total2 = tweets.classify( btc_tweets) btc_percent = (btc_positive2 / btc_total2) * 100 self.btc_sentiments.append(btc_percent) if (len(self.btc_sentiments) > 5): mean_sentiment = np.mean(self.btc_sentiments) std_sentiment = np.std(self.btc_sentiments) if btc_percent >= mean_sentiment + ( (0.800 * std_sentiment) / math.sqrt(len(self.btc_sentiments))): price = self.api.getticker('BTC-ETH') self.currentClose = price['Bid'] trade.close(self.currentClose) else: time.sleep(60 * 3) elif (self.type_of_trade == 'ETH'): ethereum_query = 'Ethereum OR ETH OR $ETH' eth_tweets, sinceid_recent = tweets.get_tweets( 10, 0, ethereum_query) eth_total_score2, eth_positive2, eth_negative2, eth_total2 = tweets.classify( eth_tweets) eth_percent = (eth_positive2 / eth_total2) * 100 self.eth_sentiments.append(eth_percent) if (len(self.eth_sentiments) > 5): mean_sentiment = np.mean(self.eth_sentiments) std_sentiment = np.std(self.eth_sentiments) if eth_percent <= mean_sentiment - ( (0.674 * std_sentiment) / math.sqrt(len(self.eth_sentiments))): price = self.api.getticker('BTC-ETH') self.currentClose = price['Bid'] trade.close(self.currentClose) else: time.sleep(60 * 3) else: price = self.api.getticker('BTC-ETH') self.currentClose = price['Bid'] trade.close(self.currentClose)