def __init__(self): self.vars = botVariables() self.investement = self.vars.initialInvestment self.makeFee = self.vars.makeFee self.takeFee = self.vars.takeFee self.output = BotLog() self.prices = [] self.closes = [] # Needed for Momentum Indicator self.trades = [] self.numOfTrades = 0 self.currentPrice = "" self.currentTime = "" self.currentClose = "" self.numSimulTrades = 1 self.indicators = BotIndicators() self.absMargin = 0 self.relMargin = 0 #these are the values of the indicators qat each endTime self.SMA1 = 0 self.SMA2 = 0 self.EMA1 = 0 self.EMA2 = 0 self.RSI = 0 self.BollUp = 0 self.BollDown = 0
def __init__(self): self.output = BotLog() self.prices = [] self.trades = [] self.currentPrice = "" self.numSimulTrades = 1 self.indicators = BotIndicators()
def __init__(self): #connect; read and write to db self.TradeDatabase = TradeDatabase() self.TradeDatabase.connect() #amount to trade (capital): self.amountInUSD = 300 #prices information self.prices = [] self.currentPrice = "" #graph and indicators self.output = BotLog() self.indicators = BotIndicators() #self.graphdataPoints = [] self.dataDate = "" self.SMA = "" self.CResistance = 0.0 self.EMA9 = [] self.MACD = [] #trade details self.tradePlaced = [] self.typeOfTrade = [] self.cumulatedProfits = 0.0 #wins and loses self.numofwins = 0 self.numofloses = 0
def __init__(self): self.output = BotLog() self.prices = [] self.currentPrice = "" self.indicators = BotIndicators() self.GRC_bal = False self.BTC_bal = False self.Total_bal = False self.can_buy = False self.can_sell = False self.trade_amount = .00059 # BTC self.to_buy = False self.to_sell = False self.pair = 'BTC_GRC' self.order_num = False self.orders = [] self.high_bid_price = False self.low_ask_price = False self.low_ask_amount = False self.high_bid_amount = False self.price_to_buy = False self.price_to_sell = False self.openTrades = [] self.open_Bids = [] self.open_Asks = [] self.orders = [] self.last_sell_price = False self.last_buy_price = False self.open_sell_flag = False self.open_buy_flag = False self.raw_spread = 0 self.mod_spread = 0 self.place_orders_flag = True
def __init__(self, pair, period): BotStrategy.__init__(self, pair, period) self.highs = [] self.lows = [] self.closes = [] self.current_price = "" self.pair = pair self.stop_loss_percent = 2.5 self.indicators = BotIndicators() self.macd_fast = 12 self.macd_slow = 26 self.macd_signal = 9 self.macd_period = self.macd_signal + self.macd_slow # Number of data points needed to use MACD indicator self.hist_period = max(self.macd_fast, self.macd_slow, self.macd_signal, self.macd_period) self.max_hist = 0 # Used to keep track of the maximum value of the MACD histogram used on this trade. # Prime the bot with past data. self.past_typical_prices, self.past_opens, self.past_closes, self.past_highs, self.past_lows = self.get_past_prices( self.period, self.hist_period) if self.past_typical_prices and self.past_closes and self.past_highs and self.past_lows and self.past_opens: self.prices = self.past_typical_prices self.closes = self.past_closes self.highs = self.past_highs self.lows = self.past_lows
def __init__(self, backtest=True, forwardtest=True): self.output = BotLog() self.pair = shared.exchange['pair'] self.coinsInOrder = shared.exchange['coinsInOrder'] self.marketInOrder = shared.exchange['marketInOrder'] self.trades = [] self.currentPrice = "" self.currentClose = "" self.lowestAsk = 0.00 self.highestBid = 0.00 self.simultaneousTrades = 4 self.tradeMultiplier = 0.1 self.ticker = {} self.backTest = backtest self.forwardTest = forwardtest self.indicators = BotIndicators() self.candlesticks = [] self.movingAverages = [] self.movingAveragePeriod = shared.strategy['movingAverageLength'] self.trueRanges = [] self.averageTrueRanges = [] # portfolio self.openOrders = [] #api self.api = BotApi()
def __init__(self, backtest=True, live=False): self.output = BotLog() self.pair = shared.exchange['pair'] self.coinsInOrder = shared.exchange['coinsInOrder'] self.marketInOrder = shared.exchange['marketInOrder'] self.trades = [] self.currentPrice = "" self.currentClose = "" self.live = live self.lowestAsk = 0.00 self.highestBid = 0.00 self.simultaneousTrades = 1 self.tradeMultiplier = 1 self.ticker = {} self.backTest = backtest self.indicators = BotIndicators() self.candlesticks = [] self.movingAverages = [] self.movingAveragePeriod = 3 self.trueRanges = [] self.averageTrueRanges = [] self.openOrders = [] # API self.api = BotApi()
def __init__(self): self.output = BotLog() self.prices = [] self.closes = [] # Needed for Momentum Indicator self.trades = [] self.currentPrice = "" self.currentClose = "" self.numSimulTrades = 1 self.indicators = BotIndicators()
def __init__(self): self.result = 0 self.output = BotLog() self.prices = [] self.positions = [] self.low = [] self.high = [] self.current_price = "" self.indicators = BotIndicators() self.num_simulpositions = 1
def __init__(self): self.output = BotLog() self.prices = [] self.closes = [] # Needed for Momentum Indicator self.trades = [] self.currentPrice = "" self.currentClose = "" self.numSimulTrades = 10 self.indicators = BotIndicators() self.totalProfit = 0.0 self.minRSI = 30 self.maxRSI = 70 self.minMomentum = 103 self.maxMomentum = 97
def __init__(self, short_mode=False, backtest=True): self.capital = 1000 self.output = BotLog() self.prices = [] self.trades = [] self.low = [] self.high = [] self.currentPrice = "" self.numSimulTrades = 100000000 # inutile si seulement signaux ! self.indicators = BotIndicators() # self.stopLoss = 2 * self.indicators.average_true_range(self.high,self.low,self.prices) self.stopLoss = 0 # inutile pour signaux self.short_mode = short_mode self.backtest = backtest
def __init__(self, name, mode, pair, numTrades, startUSD, startUnit, tradeAmount, stopLoss, targetPrice, backtest, output): self.output = output self.name = name self.mode = mode self.pair = pair self.numTrades = numTrades self.startUSD = startUSD self.startUnit = startUnit self.tradeAmount = tradeAmount self.stopLoss = stopLoss self.targetPrice = targetPrice self.backtest = backtest self.prices = [] self.closes = [] self.trades = [] self.upperBBand = [] self.lowerBBand = [] self.midBBand = [] self.MACDDiff = [] self.MACDSignal = [] self.rsi = [] self.date = "" self.action = [] self.dataPoints = [] self.balancePoints = [] self.MACDPoints = [] self.rsiPoints = [] self.currentPrice = "" self.currentClose = "" self.holdingsUSD = startUSD self.holdingsUnits = startUnit self.balance = startUSD self.balanceNoTrade = startUSD self.profit = 0 self.fees = 0 self.indicators = BotIndicators() self.priceAverage = 0
def __init__(self): self.output = BotLog() self.prices = [] self.opens = [] self.closes = [] #for Momentum self.trades = [] self.MACD_History = [] # MACD History self.MACD_Signal_History = [] # MACD Signal History self.currentPrice = None self.numSimulTrades = 1 self.takeProfit = 0.0001 self.stopLoss = 1 self.indicators = BotIndicators() self.trendPeriod = 3 # ETH : 3 # DASH : 3 self.minVolume = 1.2 # ETH : 1.2 # DASH : 1
def __init__(self, pair, period): BotStrategy.__init__(self, pair, period) self.highs = [] self.lows = [] self.closes = [] self.moving_avgs = [] # Keep track of MAs self.ma_slopes = [] # Keep track of Slope of MAs self.slope_difference = [] self.support_levels = [] self.resistance_levels = [] self.current_price = "" self.pair = pair self.stoch_stop_loss = 2.5 self.cool_down_period = 0 self.indicators = BotIndicators() # Lookback window sizes self.stoch_period = 5 # n previous candles for stochastic indicator self.ma_period_fast = 9 # n previous candles for fast moving average indicator self.ma_slope_lookback = 9 # n previous values for calculating slope of MA. self.ma_period_slow = 26 # n previous candles for slow moving average indicator self.sr_period = 700 # n previous candles for support/resistance self.sr_n = 25 # n-value for S/R indicator. Controls Smoothing. self.hist_period = max(self.stoch_period, self.sr_period, self.ma_period_fast, self.ma_period_slow) self.over_bought = 80 self.over_sold = 20 self.mid_line = 50 self.stoch_ready_to_buy = False # Prime the bot with past data. self.past_typical_prices, self.past_opens, self.past_closes, self.past_highs, self.past_lows = self.get_past_prices(self.period, self.hist_period) if self.past_typical_prices and self.past_closes and self.past_highs and self.past_lows and self.past_opens: self.prices = self.past_typical_prices self.closes = self.past_closes self.highs = self.past_highs self.lows = self.past_lows for i in reversed(range(self.ma_period_fast)): sub_slice = self.prices[:-i - 1] _ma = self.indicators.moving_average(sub_slice[-self.ma_period_fast:], self.ma_period_fast) self.moving_avgs.append(_ma)
def __init__(self, period, log, api, checker, stopLoss=0, startBalance=100): self.highs = {} self.lows = {} self.closes = {} self.dates = [] self.volumes = {} self.MFIs = {} self.MACD = {} self.MovingAverage = {} self.output = log self.api = api self.fee = {} self.fee['BTC'] = self.api.getFee('ETHBTC') self.fee['BNB'] = self.api.getFee('BNBBTC') self.fee['USDT'] = self.api.getFee('BTCUSDT') self.pairs = checker.pairs self.coins = checker.coins self.indicators = BotIndicators(period, self.pairs) # unused, but find application self.stopLoss = stopLoss # self.balance = {i: 0 for i in checker.coins} # disable (it has to be in the tick method below) # setting start values for USDT # self.balance['USDT'] = startBalance self.oldValue = 0 self.ovrValue = 0 self.MFIs = {} self.MovingAverage = {} self.MFI = None self.period = period self.counter = 0
def __init__(self, period, startTime, endTime, backTest=True): self.exchange = shared.exchange['name'] self.pair = shared.exchange['pair'] self.period = int(period) self.startTime = int(startTime) self.endTime = int(endTime) self.backTest = bool(backTest) self.output = BotLog() self.tempCandle = None self.indicators = BotIndicators() self.data = [] self.api = BotApi() if backTest: self.data = self.api.returnChartData(self.pair, period=int(self.period), start=self.startTime, end=self.endTime)
def __init__(self): self.output = BotLog() self.prices = [] self.closes = [] # Needed for Momentum Indicator self.trades = [] self.currentPrice = "" self.numSimulTrades = 1 self.indicators = BotIndicators() self.type_trade = False self.GRC_bal = False self.BTC_bal = False self.Total_bal = False self.can_buy = False self.to_buy = False self.to_sell = False self.pair = 'BTC_GRC' self.order_num = False self.balance = False self.sell_price_last = False self.buy_price_last = False self.loss_break = 0 self.orders = [] self.high_bid_price = False self.low_ask_price = False self.low_ask_amount = False self.high_bid_amount = False self.price_to_buy = False self.price_to_sell = False self.short_MA_period = 12 self.long_MA_period = 26 self.signal_MA_period = 9 self.winsound = winsound self.frequency = 2500 # Set Frequency To 2500 Hertz self.duration = 1000 # Set Duration To 1000 ms == 1 second self.short_EMA_list = [] self.long_EMA_list = [] self.MACD_list = [] self.MACD_sig_list = [] self.MACD_hist_list = [] self.openTrades = []
def __init__(self, pair): if (not config.CONFIG["VERBOSE"]): print("Calculating indicators") self.pair = pair self.output = BotLog() self.path = config.CONFIG['PATH'] self.prices = [] self.closes = [] self.trades = [] self.movingAVG = [] self.momentum = [] self.RSI = [] self.currentPrice = "" self.currentClose = "" self.numSimulTrades = 1 self.indicators = BotIndicators() self.graph_data = { "date": [], "movingAverage": [], "momentum": [], "RSI": [] }
def __init__(self, pair, period): BotStrategy.__init__(self, pair, period) self.highs = [] self.lows = [] self.closes = [] self.currentPrice = "" self.pair = pair self.stoch_stop_loss = 100.0 self.indicators = BotIndicators() self.stoch_period = 14 # n previous trading sessions (candles) self.over_bought = 80 self.over_sold = 20 self.past_avg_prices, self.past_opens, self.past_closes, self.past_highs, self.past_lows = self.get_past_prices( self.period, self.stoch_period) if self.past_avg_prices and self.past_closes and self.past_highs and self.past_lows and self.past_opens: self.prices = self.past_avg_prices self.closes = self.past_closes self.highs = self.past_highs self.lows = self.past_lows
def __init__(self, strat, chartmax, chartmin, chartlengths, pair, numofcharts, valuesAre, timestamps, extra, valuelist, intervals, beginag, endag, tlen, live=False, aggTrades=True, aggisNext=True, graphics=True, ma5on=True, handlon=True): self.masterDick = {} self.graphics = graphics #If we want these indicators graphed: self.ma5on = ma5on #***************************# #read api token from text file, hopefully I don't accidentally upload the text file to github lol f = open("token.txt", "r") contents = f.read() newline = False secretkey = "" apikey = "" for x in contents: if x == "\n": newline = True continue if not newline: apikey += x else: secretkey += x self.client = Client(apikey, secretkey) f.close() #### self.strat = strat self.stratlist = [ "", "self.firstone(lows, highs, k, o)#, nextTradeSeller)", "self.secondone(lows, highs, k, o)", "self.thirdone()" ] #this checks if ur trading larger(not fractional) currencies (BTCUSD, etc) self.largerpair = False largepairlist = ["BTCUSDT"] for f**k in largepairlist: if pair == f**k: self.largerpair = True self.aggisNext = aggisNext self.aggTrades = aggTrades #price change during market buying self.amtofups = 0 self.amtofdowns = 0 self.pair = pair self.indicators = BotIndicators() self.live = live #self.rsifirst = True self.rsiper = 12 self.stochper = 14 self.bollingerper = 20 self.chartlen = chartlengths self.last = False self.bigma = 0 self.ma15 = 0 self.ma5 = 0 self.bolup = 0 self.bollow = 0 self.bolmid = 0 self.bandwidth = 0 #BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB #BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB #slutty variables turned global #if u wanna call functions that used to take params like chartnumber, nextTrade, etc. but with a different chartnumber #or price or whatever, just update global chartnumber or whatevs, call the function, then set the var back to what it was self.price = 0 self.nextTrade = 0 self.chartnumber = 0 #doin these now self.high = 0 self.low = 0 #coins available to spend #A little f****d for larger pair, startbtc is going to actually be usdt if self.largerpair: #base is in USDT self.startbase = 100 else: #base is in BTC self.startbase = 10 self.availablebase = self.startbase #self.firstbuy = self.availablebase / 2.0 #self.secondbuy = self.availablebase - self.firstbuy self.amtofalt = 0 #self.secondtradeentries = 0 self.totalentries = 0 #how many trades can there be self.entries = 1 #stop loss percent self.stopPercent = 10 listofvars = [ "crosstime", "firstcross", "crossPointA", "crossPointB", "percentlist", "count", "currentPrice", "prices", "ma5list", "ma15list", "ma15", "ma5", "pchange", "ma5lower", "ma5higher", "lmaxes", "lmins", "ema", "rsi", "rsilist", "botmax", "botmin", "pricechg", "pag", "pal", "rsifirst", "highs", "lows", "stochfirst", "k", "fast", "bigma", "bigmalist", "bolup", "bolmid", "bollow", "bandwidth" ] ''' Vars Explained: crosstime idk firstcross idk crossPointA idk crossPointB idk percentlist list for how much price has gone up/down percentage-wise for each ticker. Usually compared to last price, is changeable though count i think -tick number currentPrice prices ma5list ma15list ma15 ma5 pchange ma5lower ma5higher lmaxes lmins ema rsi rsilist ''' for i in range(numofcharts): for item in range(len(listofvars)): key = listofvars[item] + str(i + 1) self.masterDick[key] = valuelist[item] print(self.masterDick) if self.graphics: self.graph = Graph(chartmax, chartmin, self.chartlen, pair, numofcharts, valuesAre, timestamps, extra, intervals, self.rsiper, self.stochper, self.bollingerper, ma5on=ma5on, handlon=handlon) #This only works for one chart at the moment self.entryprices = [] #U still need to deal with self.orderPercent listoforder = ["orderPercent", "avgentryprice"] ordervals = [0, 0] self.orders = {} for num in range(numofcharts): for thing in range(len(listoforder)): key = listoforder[thing] + str(num + 1) self.orders[key] = ordervals[thing] print(self.orders) self.dentry = {} #setting number of allowed entries: #NEED TO DELETE THESE FROM ABOVE LOOP entryshit = [ "placedOrder", "orderPrice", "orderGain", "buy", "tradeEntries" ] entvals = [False, 0, 0, 0, 0] for n in range(numofcharts): for entr in range(1, self.entries + 1): for i in range(len(entryshit)): key = entryshit[i] + str(entr) + str(n + 1) self.dentry[key] = entvals[i] self.prevEma = 0 #I'm lazy, we definitely can't run more than one chart now self.prevbigma = 0 self.prevma15 = 0 self.prevma5 = 0 self.prevma15list = [] self.prevma5list = [] self.prevbigmalist = [] self.prevPrices = [] self.prevPrevEma = 0 self.prevk = [] self.prevfast = 0 self.prevhighs = [] self.prevlows = [] self.prevrsi = 0 self.prevpag = 0 self.prevpal = 0 self.prevPriceChg = [] #Bollinger self.prevBolUp = 0 self.prevBolMid = 0 self.prevBolLow = 0 #analytical self.upcount = 0 self.downcount = 0 self.downsnups = {} '''
def __init__(self, exchange, pair, period, startTime, endTime, backtest=True): self.botHTML = BotHTML() self.vars = botVariables() self.api_key = self.vars.api_key_poloniex self.api_secret = self.vars.api_secret_poloniex self.avPeriod = self.vars.movingAvPeriod self.indicators = BotIndicators() self.pair = pair self.period = period self.startTime = startTime self.endTime = endTime self.data = [] self.prices = [] self.poloData = [] self.trades = [] if (exchange == "poloniex"): print('Ecxhange with Poloniex') self.conn = poloniex.Poloniex(self.api_key, self.api_secret) if backtest: print("Checking the data from " + datetime.datetime.fromtimestamp(int(startTime)).strftime( '%Y-%m-%d %H:%M:%S') + " to " + datetime.datetime.fromtimestamp(int(endTime)).strftime( '%Y-%m-%d %H:%M:%S')) self.poloData = self.conn.returnChartData( self.pair, self.period, self.startTime, self.endTime) #A:poloData is an list (checked with the funtion type(), where each item of the list contains 6 values of the period for datum in self.poloData: #datum is a dict = {key1:value1, key2:value2, ... } if (datum['open'] and datum['close'] and datum['high'] and datum['low']): #putting all this data to the BotCandlestick object self.data.append( BotCandlestick(self.period, datum['open'], datum['close'], datum['high'], datum['low'], datum['weightedAverage'], datum['date'])) if (exchange == "binance"): # Remember to install binance python script with --> pip install python-binance print('Ecxhange with Binance') if backtest: # create the Binance client, no need for api key client = Client("", "") klines = client.get_historical_klines( self.vars.pairBinance, getattr(client, self.vars.periodBinance), self.vars.startTimeBinance, self.vars.endTimeBinance) for kline in klines: self.data.append( BotCandlestick( self.period, kline[1], kline[4], kline[2], kline[3], str((float(kline[1]) + float(kline[2]) + float(kline[4]) + float(kline[3])) / 4), int(((kline[0]) + (kline[6])) / 2000))) #because in miliseconds """
def __init__(self, startingBal): self.output = BotLog() self.trades = [] self.candlesticks = [] self.indicators = BotIndicators() self.currentBal = startingBal
class RoyTrader(): client = Client(api_key, api_secret) user = client.get_current_user() account = client.get_accounts() buys = [] sells = [] prices = [] signals = [] args = [] fibo = BotIndicators() #print(account) print('Trading As: %s (%s)' % (user['name'], user['email'])) #print ('Starting Balance: $%s (%s BTC @ $%s/BTC)' % (balance['EUR'], balance['BTC'], get_price())) def __init__(self, api_key, api_secret): #coinbase #poloniex self.startTrading() def startTrading(self): #prices = [] currentMovingAverage = 0 startTime = False endTime = False historicalData = False tradePlaced = False typeOfTrade = False dataDate = "" orderNumber = "" market_fees = 0.15 # coinbase per-transaction fee in dollars min_profit_margin = 2.0 # minimum price increase before we sell out MACD = 0 if webserver: WebServer.init_Webserver() WebServer.start_Webserver() idloop = 0 while True: try: if idloop < lengthOfMA: idloop = idloop + 1 if strategy == "classic": self.classic_strategy() elif strategy == "MACD": self.MACD_Strategy(idloop) time.sleep(int(period)) except KeyboardInterrupt: print("Bye") if webserver: WebServer.stop_Webserver() sys.exit() def MACD_Strategy(self, idloop): vectorEMAS_AMAF_MACD = [] MACD = 0 MACD_point = 0 RSI_point = 0 lastprice = self.get_price(pair) buyprice = self.get_buy_price() sellprice = self.get_sell_price() currentMovingAverage = 0 previousPrice = 0 emaSlow = 0 emaFast = 0 dataDate = datetime.datetime.now().strftime('%H:%M:%S') #RSI = self.fibo.rsiFunc(self.prices) if len(self.args) > 1: currentMovingAverage = sum(self.prices) / float(len(self.prices)) #elif len(self.args)>12: #emaFast condition #elif len(self.args)>14: #RSI condition appendLine = datetime.datetime.now( ), lastprice, buyprice, sellprice, previousPrice, 2 self.args.append(appendLine) self.prices.append(float(lastprice)) if len(self.args) > 26: vectorEMAS_AMAF_MACD = self.fibo.MACD(self.prices) emaSlow = vectorEMAS_AMAF_MACD[0] emaFast = vectorEMAS_AMAF_MACD[1] MACD = vectorEMAS_AMAF_MACD[2] MACD_point = MACD[0] RSI = self.fibo.rsiFunc(self.prices) RSI_point = RSI[0] print(idloop, " Date: ", str(dataDate), " Period: ", str(period), " coppia: ", str(pair), " Price: ", str(lastprice), " BUY: ", buyprice, "SELL: ", sellprice, " EMA: ", str(currentMovingAverage), " MACD: ", str(MACD_point), " RSI: ", RSI_point) if len(self.args) > 27: self.findSignals(self.args, RSI, MACD) if graphical: self.fibo.plot3(self.args, self.prices, self.signals, emaSlow, emaFast, MACD, RSI) if len(self.args) == lengthOfMA: self.prices.pop(0) self.args.pop(0) if len(self.signals) > 0: #print("data first signal:", self.signals[0][0]) #print("data first args:", self.args[0][0]) if self.signals[0][0] < self.args[0][0]: self.signals.pop(0) print( "************************** SIGNALS POPPED *******************************" ) @property def get_account(self): return [ acct for acct in self.client.get_accounts()['data'] if acct['balance']['currency'] == 'BTC' ][0] @property def get_balance(self): return { account['balance']['currency']: float(account['balance']['amount']), account['native_balance']['currency']: float(account['native_balance']['amount']), } def get_price(self, pair): return float(self.client.get_spot_price(currency_pairo=pair)['amount']) def get_price_LTC(self): print(self.client.get_spot_price(currency_pair=pair)) def get_buy_price(self): return float(self.client.get_buy_price(currency_pair=pair)['amount']) def get_sell_price(self): return float(self.client.get_sell_price(currency_pair=pair)['amount']) def buy(self, amount): buy_obj = self.account.buy(amount, 'EUR') self.buys.append(buy_obj) def sell(self, amount): sell_obj = self.account.sell(amount, 'EUR') self.sells.append(sell_obj) def localbuy(self, amount, price): buy_obj = json.dumps({ 'date': str(datetime.datetime.now()), 'amount': amount, 'price': price }) self.buys.append(buy_obj) with open("www/report.csv", "a") as myfile: myfile.write("BUY," + str(datetime.datetime.now()) + "," + str(amount) + "," + str(price) + "," + str(price * amount) + "\n") myfile.close() def localsell(self, amount, price): sell_obj = json.dumps({ 'date': str(datetime.datetime.now()), 'amount': amount, 'price': price }) self.sells.append(sell_obj) with open("www/report.csv", "a") as myfile: myfile.write("SELL," + str(datetime.datetime.now()) + "," + str(amount) + "," + str(price) + "," + str(price * amount) + "\n") myfile.close() def bytedate2num(self, fmt): def converter(b): return mdates.strpdate2num(fmt)(b.decode('ascii')) return converter def bytespdate2num(self, fmt, encoding='utf-8'): strconverter = mdates.strpdate2num(fmt) def bytesconverter(b): s = b.decode(encoding) return strconverter(s) return bytesconverter def findSignals(self, args, RSI, MACD): date = [x[0] for x in args] prices = [x[1] for x in args] buyprices = [x[2] for x in args] sellprices = [x[3] for x in args] lastprice = prices[-1] buyprice = buyprices[1] sellprice = sellprices[-1] if MACD[-1] > 0 and MACD[-2] < 0 and MACD[-3] < 0 and MACD[-4] < 0: self.signals.append([date[-1], float(lastprice), "buy", "MACD"]) print( str(date[-1]) + " *** MACD *** BUY SIGNAL INTERCEPTED @ " + str(lastprice)) if MACD[-1] < 0 and MACD[-2] > 0 and MACD[-3] > 0 and MACD[-4] > 0: self.signals.append([date[-1], float(lastprice), "sell", "MACD"]) print( str(date[-1]) + " *** MACD *** SELL SIGNAL INTERCEPTED @ " + str(lastprice)) if RSI[-1] < 20 and RSI[-2] > 20 and RSI[-3] > 20 and RSI[-4] > 20: self.signals.append([date[-1], float(lastprice), "buy", "RSI"]) print( str(date[-1]) + " *** RSI *** BUY SIGNAL INTERCEPTED @ " + str(lastprice)) elif RSI[-1] > 80 and RSI[-2] < 80 and RSI[-3] < 80 and RSI[-4] < 80: self.signals.append([date[-1], float(lastprice), "sell", "RSI"]) print( str(date[-1]) + " *** RSI *** SELL SIGNAL INTERCEPTED @ " + str(lastprice)) buycountsRSI = 0 buycountsMACD = 0 sellcountsRSI = 0 sellcountsMACD = 0 for idx, sign in enumerate(self.signals): if sign[2] == "buy": if sign[3] == "RSI": buycountsRSI = buycountsRSI + 1 if sign[3] == "MACD": buycountsMACD == buycountsMACD + 1 if sign[2] == "sell": if sign[3] == "RSI": buycountsRSI = sellcountsRSI + 1 if sign[3] == "MACD": buycountsMACD == sellcountsMACD + 1 if buycountsMACD + buycountsRSI == 2: self.localbuy(2, buyprice) if sellcountsMACD + sellcountsRSI == 2 and gainCheck(sellprice): self.localsell(2, sellprice) def percent(self, part, whole): return 100 * float(part) / float(whole) def percentage(self, percent, whole): return (percent * whole) / 100.0 def gainCheck(self, sellprice): for idx, buy in enumerate(self.buys): resp = json.loads(buy) if percent( (float(sellprice) - (float(resp['price']) - float(market_fees)), buyprice)) > 0: print( "GAIN %:", float(sellprice) - (float(buyprice) - float(market_fees))) return True else: return False
class RoyTrader(): client = Client(api_key, api_secret) user = client.get_current_user() account = client.get_accounts() #tbuys = client.get_buys() buys = [] sells = [] prices = [] signals = [] args = [] transactions_plot = [] fibo = BotIndicators() buy_count = 0 #print(account) print ('Trading As: %s (%s)' % (user['name'], user['email'])) #print ('Starting Balance: $%s (%s BTC @ $%s/BTC)' % (balance['EUR'], balance['BTC'], self.get_price())) print (account) def __init__(self, api_key, api_secret): #coinbase #poloniex self.startTrading() def startTrading(self): #prices = [] currentMovingAverage = 0; startTime = False endTime = False historicalData = False tradePlaced = False typeOfTrade = False dataDate = "" orderNumber = "" market_fees = 0.15 # coinbase per-transaction fee in dollars min_profit_margin = 2.0 # minimum price increase before we sell out MACD = 0 if webserver: try: WebServer.initialize_web_server() except Exception as e: raise e finally: WebServer.stop_web_server() idloop = 0 #self.sync_buys_sells_operations() while True: try: if idloop < lengthOfMA: idloop = idloop + 1 if strategy == "RSI": self.classic_strategy() elif strategy == "MACD": self.MACD_Strategy() elif strategy == "combined": self.MACD_RSI_Strategy(idloop) time.sleep(int(period)) except KeyboardInterrupt: print("Bye") if webserver: WebServer.stop_web_server() sys.exit() def MACD_Strategy(self): vectorEMAS_AMAF_MACD = [] MACD = 0 MACD_point = 0 RSI_point = 0 #lastprice = self.get_price(pair) lastprice = self.get_sell_price(pair) # use sell price instead of spot_price for more precise value buyprice = self.get_buy_price(pair) sellprice = self.get_sell_price(pair) currentMovingAverage = 0 previousPrice = 0 emaSlow = 0 emaFast = 0 dataDate = datetime.datetime.now().strftime('%H:%M:%S') if len(self.args)>1: currentMovingAverage = sum(self.prices) / float(len(self.prices)) appendLine = datetime.datetime.now(),lastprice,buyprice,sellprice,previousPrice, 2 self.args.append(appendLine) self.prices.append(float(lastprice)) if len(self.args) > 26: vectorEMAS_AMAF_MACD = self.fibo.MACD(self.prices) emaSlow = vectorEMAS_AMAF_MACD[0] emaFast = vectorEMAS_AMAF_MACD[1] MACD = vectorEMAS_AMAF_MACD[2] MACD_point = MACD[-1] RSI = self.fibo.rsiFunc(self.prices) RSI_point = RSI[-1] print ("Date: ",str(dataDate)," Pair: ",str(pair)," Price: ",str(lastprice)," BUY: ", buyprice, "SELL: ", sellprice ," EMA: ",str(currentMovingAverage)," MACD: ",str(MACD_point), " RSI: ", RSI_point) if len(self.args) > 27: transactions_plot = self.findSignals_MACD(self.args, RSI, MACD) if graphical: self.fibo.plot3(self.args, self.prices, self.signals,emaSlow, emaFast, MACD, RSI, transactions_plot) if len(self.args) == lengthOfMA: self.prices.pop(0) self.args.pop(0) #if len(self.signals) > int(ignore_signals_after): #self.signals.pop(0) #print("************************** SIGNALS POPPED *******************************" ) if len(self.signals) > 0 and len(self.args) > ignore_signals_after and self.signals[0][0] < self.args[-(ignore_signals_after)][0]: self.signals.pop(0) print("************************** SIGNALS POPPED *******************************" ) def MACD_RSI_Strategy(self, idloop): vectorEMAS_AMAF_MACD = [] MACD = 0 MACD_point = 0 RSI_point = 0 #lastprice = self.get_price(pair) lastprice = self.get_sell_price(pair) # use sell price instead of spot_price for more precise value buyprice = self.get_buy_price(pair) sellprice = self.get_sell_price(pair) currentMovingAverage = 0 previousPrice = 0 emaSlow = 0 emaFast = 0 dataDate = datetime.datetime.now().strftime('%H:%M:%S') if len(self.args)>1: currentMovingAverage = sum(self.prices) / float(len(self.prices)) appendLine = datetime.datetime.now(),lastprice,buyprice,sellprice,previousPrice, 2 self.args.append(appendLine) self.prices.append(float(lastprice)) if len(self.args) > 26: vectorEMAS_AMAF_MACD = self.fibo.MACD(self.prices) emaSlow = vectorEMAS_AMAF_MACD[0] emaFast = vectorEMAS_AMAF_MACD[1] MACD = vectorEMAS_AMAF_MACD[2] MACD_point = MACD[-1] RSI = self.fibo.rsiFunc(self.prices) RSI_point = RSI[-1] print ("Date: ",str(dataDate)," Pair: ",str(pair)," Price: ",str(lastprice)," BUY: ", buyprice, "SELL: ", sellprice ," EMA: ",str(currentMovingAverage)," MACD: ",str(MACD_point), " RSI: ", RSI_point) if len(self.args) > 27: transactions_plot = self.findSignals_MACD_RSI(self.args, RSI, MACD) if graphical: self.fibo.plot3(self.args, self.prices, self.signals,emaSlow, emaFast, MACD, RSI, transactions_plot) if len(self.args) == lengthOfMA: self.prices.pop(0) self.args.pop(0) #if len(self.signals) > int(ignore_signals_after): #self.signals.pop(0) #print("************************** SIGNALS POPPED *******************************" ) if len(self.signals) > 0 and len(self.args) > ignore_signals_after and self.signals[0][0] < self.args[-(ignore_signals_after)][0]: self.signals.pop(0) print("************************** SIGNALS POPPED *******************************" ) @property def get_account(self): return [acct for acct in self.client.get_accounts()['data'] if acct['balance']['currency'] == 'BTC'][0] @property def get_balance(self): return { account['balance']['currency']: float(account['balance']['amount']), account['native_balance']['currency']: float(account['native_balance']['amount']), } @property def account(self): return [acct for acct in self.client.get_accounts()['data'] if acct['balance']['currency'] == 'BTC'][0] @property def balance(self): return { self.account['balance']['currency']: float(self.account['balance']['amount']), self.account['native_balance']['currency']: float(self.account['native_balance']['amount']), } def get_price(self,pair): return float(self.client.get_spot_price(currency_pair = pair)['amount']) def get_price_LTC(self): print (self.client.get_spot_price(currency_pair = pair)) def get_buy_price(self, pair): return float(self.client.get_buy_price(currency_pair = pair)['amount']) def get_sell_price(self, pair): return float(self.client.get_sell_price(currency_pair = pair)['amount']) def buy(self, amount): buy_obj = self.account.buy(amount, 'EUR') self.buys.append(buy_obj) self.transactions_plot.append([date, float(price), "BUY"]) with open("transactions/BUY_Report", "a") as buyfile: buyfile.write(buy_obj+"\n") buyfile.close() def sell(self, amount): sell_obj = self.account.sell(amount, 'EUR') self.sells.append(sell_obj) self.transactions_plot.append([date, float(price), "SELL"]) with open("transactions/SELL_Report", "a") as sellfile: sellfile.write(sell_obj+"\n") sellfile.close() def localbuy(self, date, amount, price): buy_obj = json.dumps({'date': str(date),'amount': amount, 'price': price}) self.buys.append(buy_obj) self.transactions_plot.append([date, float(price), "BUY"]) with open("www/report.csv", "a") as myfile: myfile.write("BUY,"+ str(date)+","+str(amount)+","+str(price)+","+str(int(price*amount))+"\n") myfile.close() with open("www/index.html", "a") as htmlreport: htmlreport.write("<br> BUY Operation at: " + str(date) +" <b>amount:</b> "+str(amount)+" <b> buy price:</b>"+str(price)+" <b>total:</b> "+str(int(price*amount))+"\n") htmlreport.close() def localsell(self,date, amount, price): sell_obj = json.dumps({'date': str(date), 'amount': amount, 'price': price}) self.sells.append(sell_obj) self.transactions_plot.append([date, float(price), "SELL"]) with open("www/report.csv", "a") as myfile: myfile.write("SELL,"+ str(date)+","+str(amount)+","+str(price)+","+str(price*amount)+"\n") myfile.close() with open("www/index.html", "a") as htmlreport: htmlreport.write("<br> SELL Operation at: " + str(date) +" <b>amount:</b> "+str(amount)+" <b> sell price:</b>"+str(price)+" <b>total:</b> "+str(int(price*amount))+"\n") htmlreport.close() def sync_buys_sells_operations(self): json_buys = self.client.get_buys() print(json_buys) ''' for idx, gdax_buy in enumerate(self.buys): resp = json.loads(buy) if percent((float(sellprice)-(float(resp['price'])-float(market_fees)),buyprice)) > 0: print("GAIN %:", float(sellprice)-(float(buyprice)-float(market_fees))) return True else: return False ''' def get_buy_count(self): print("pre buy count") global buy_count buy_count = len(self.buys) print("after buy count") return buy_count def bytedate2num(self, fmt): def converter(b): return mdates.strpdate2num(fmt)(b.decode('ascii')) return converter def bytespdate2num(self, fmt, encoding='utf-8'): strconverter = mdates.strpdate2num(fmt) def bytesconverter(b): s = b.decode(encoding) return strconverter(s) return bytesconverter def findSignals_MACD(self, args, RSI, MACD): date = [x[0] for x in args] prices = [x[1] for x in args] buyprices = [x[2] for x in args] sellprices = [x[3] for x in args] dataDate = datetime.datetime.now().strftime('%H:%M:%S') lastprice = prices[-1] buyprice = buyprices[-1] sellprice = sellprices[-1] if MACD[-1] > 0 and MACD[-2] < 0 and MACD[-3] < 0: self.signals.append([date[-1],float(lastprice),"buy", "MACD"]) print("Date: " + str(dataDate) + " *** MACD *** BUY SIGNAL INTERCEPTED @ " + str(buyprice)) if MACD[-1] < 0 and MACD[-2] > 0 and MACD[-3] > 0: self.signals.append([date[-1],float(lastprice),"sell", "MACD"]) print("Date: " + str(dataDate) + " *** MACD *** SELL SIGNAL INTERCEPTED @ " + str(sellprice)) if len(self.signals) > 0: if self.signals[-1][2] == "buy": if len(self.buys) < buy_limit: print("Executing BUY. Limit is:" + str(buy_limit)) self.localbuy(self.args[-1][0],buy_sell_amount,buyprice) else: print("Date: " + str(dataDate) + "BUY limit reached") elif self.signals[-1][2] == "sell": if self.gainCheckLite(sellprice): self.localsell(self.args[-1][0],buy_sell_amount,sellprice) return self.transactions_plot def findSignals_MACD_RSI(self, args, RSI, MACD): date = [x[0] for x in args] prices = [x[1] for x in args] buyprices = [x[2] for x in args] sellprices = [x[3] for x in args] dataDate = datetime.datetime.now().strftime('%H:%M:%S') lastprice = prices[-1] buyprice = buyprices[-1] sellprice = sellprices[-1] #TODO controllare i signals del periodo predecedente #TODO vendere anche senza nessun signal se il prezzo raggiunge il target if MACD[-1] > 0 and MACD[-2] < 0 and MACD[-3] < 0: self.signals.append([date[-1],float(lastprice),"buy", "MACD"]) print("Date: " + str(dataDate) + " *** MACD *** BUY SIGNAL INTERCEPTED @ " + str(buyprice)) if MACD[-1] < 0 and MACD[-2] > 0 and MACD[-3] > 0: self.signals.append([date[-1],float(lastprice),"sell", "MACD"]) print("Date: " + str(dataDate) + " *** MACD *** SELL SIGNAL INTERCEPTED @ " + str(sellprice)) if RSI[-1] < RSI_down_lim: self.signals.append([date[-1],float(lastprice),"buy", "RSI"]) print("Date: " + str(dataDate) + " *** RSI *** BUY SIGNAL INTERCEPTED @ " + str(buyprice)) elif RSI[-1] > RSI_top_lim: self.signals.append([date[-1],float(lastprice),"sell", "RSI"]) print("Date: " + str(dataDate) + " *** RSI *** SELL SIGNAL INTERCEPTED @ " + str(sellprice)) if len(self.signals) > 1: # if we have 2 according signals of buy if self.signals[-1][2] == "buy" and self.signals[-2][2] == "buy": #and if the 2 signals according for MACD and RSI if self.signals [-1][3] == "RSI" and self.signals [-2][3] == "MACD": if len(self.buys) < buy_limit: print("Executing BUY. Limit is:" + str(buy_limit)) self.localbuy(self.args[-1][0],buy_sell_amount,buyprice) elif self.signals [-1][3] == "MACD" and self.signals [-2][3] == "RSI": if len(self.buys) < buy_limit: print("Executing BUY. Limit is:" + str(buy_limit)) self.localbuy(self.args[-1][0],buy_sell_amount,buyprice) elif self.signals [-1][3] == "RSI" and self.signals [-2][3] == "RSI": self.signals.pop(-2) # if we have 2 according signals of sell elif self.signals[-1][2] == "sell" and self.signals[-2][2] == "sell": #and if the 2 signals give the same result from MACD and RSI if self.signals [-1][3] == "RSI" and self.signals [-2][3] == "MACD": #TODO: rimuovere il gaincheck. Serve vendere per riacquistare a prezzo più basso. if self.gainCheckLite(sellprice): self.localsell(self.args[-1][0],buy_sell_amount,sellprice) elif self.signals [-1][3] == "MACD" and self.signals [-2][3] == "RSI": #check if we are rich :) #TODO: rimuovere il gaincheck. Serve vendere per riacquistare a prezzo più basso. # serve vendere per evitare il down che abbiamo previsto grazie a MACD e RSI if self.gainCheckLite(sellprice): self.localsell(self.args[-1][0],buy_sell_amount,sellprice) elif self.signals [-1][3] == "RSI" and self.signals [-2][3] == "RSI": self.signals.pop(-2) # only 1 signal but hard conditions elif self.signals[-1][2] == "buy" and self.signals [-1][3] == "RSI" and (MACD[-1] > 0): if len(self.buys) < buy_limit: self.localbuy(self.args[-1][0],buy_sell_amount,buyprice) else: print("Date: " + str(dataDate) + "BUY limit reached") else: print("Date: " + str(dataDate) + " BUY signal and SELL signal discording. HOLD POSITION... ") return self.transactions_plot def percent(self, part, whole): return 100 * float(part)/float(whole) def percentage(self, percent, whole): return (percent * whole) / 100.0 def gainCheck(self, sellprice): #ensure coverage of market fees and gain target for idx, buy in enumerate(self.buys): resp = json.loads(buy) if self.percent((float(sellprice)-(float(resp['price'])-float(self.getFees(resp['amount'])))-float(self.percentage(min_profit_margin,float(resp['price'])))),float(resp['price'])) > 0: return True else: Print ("SELL ABORTED: SellPrice:", float(sellprice), " BUY Price:", float(resp['price']), " Gain:", float(sellprice)-(float(resp['price'])-float(market_fees)-float(percentage(min_profit_margin,float(resp['price']))), "% Target: ", float(percentage(min_profit_margin,float(resp['price']))), "%" )) return False def gainCheckLite(self, sellprice): #ensure coverage of market fees for idx, buy in enumerate(self.buys): resp = json.loads(buy) if self.percent((float(sellprice)-(float(resp['price'])-float(self.getFees(resp['amount'])))),float(resp['price'])) > 0: return True else: print ("SELL ABORTED: SellPrice:", float(sellprice), "< (BUY Price:", float(resp['price']), " + Market Fee:", float(market_fees),")") return False def getFees(self, amount): return (market_fees * amount) / 100
def __init__(self): self.indicators = BotIndicators()
def __init__(self, period, functions, balance, trial, details, strat, trained_model="", defTrades=[]): self.output = BotLog() self.prices = [] self.period = period self.startPrice = 0 self.closes = [] # Needed for Momentum Indicator self.trades = defTrades self.currentPrice = 0 self.startDate = "" self.currentDate = "" self.currentClose = "" self.functions = functions self.balance = balance self.origBalance = balance self.account = BotAccount(self.functions) self.account.createBalancePage() self.startingPositions = self.account.getBalance() self.indicators = BotIndicators() self.trained_model = trained_model self.dirty = True self.fee = 0.0025 self.strat = strat self.lookback = 7 if not 'lookback' in details else int( details['lookback']) self.trial = trial self.openTrades = [] self.balanceRecord = [] self.highMA = 47 if not 'highMA' in details else details['highMA'] self.lowMA = 28 if not 'lowMA' in details else details['lowMA'] self.mamultfactor = 1 if not 'maFactor' in details else details[ 'maFactor'] self.numSimulTrades = 1 if not 'simTrades' in details else details[ 'simTrades'] self.stoploss = 0 if not 'stoploss' in details else float( details['stoploss']) self.advance = 13 if not 'advance' in details else int( details['advance']) self.lowrsi = 30 if not 'lowrsi' in details else details['lowrsi'] self.highrsi = 70 if not 'highrsi' in details else details['highrsi'] self.rsiperiod = 14 if not 'rsiperiod' in details else details[ 'rsiperiod'] self.learnProgTotal = 1400 if not 'learnProgTotal' in details else int( details['learnProgTotal']) self.upfactor = 1.1 if not 'upfactor' in details else details[ 'upfactor'] self.downfactor = 1.3 if not 'downfactor' in details else details[ 'downfactor'] self.trailingstop = 0.1 if not 'trailingstop' in details else details[ 'trailingstop'] self.prev_run_time = 0 if not 'running_time' in details else int( details['running_time']) self.stoploss_day_count = 0 self.stoploss_day_count_set = 0 if not 'stoplossDayCount' in details else details[ 'stoplossDayCount'] # initiate any trades left over from last time for trade in self.trades: trade.stopLoss = trade.entryPrice * (1 - self.stoploss) if '4' in self.strat: trade.expiry = self.advance trade.log = self.trial