def main(argv): period = 10 ########### API KEYS ########### #Binance b_api_key = 'newb' b_api_secret = 'noob' #HitBTC h_api_key = 'nub' h_api_secret = '...' #### Client Declarations #### b_client = Client(b_api_key, b_api_secret) h_client = H_Client("https://api.hitbtc.com", h_api_key, h_api_secret) ############# #Get Market Depth depth = b_client.get_order_book(symbol='BNBBTC') #Get Recent Trades trades_recent = b_client.get_recent_trades(symbol='BNBBTC') #Get Historical Trades trades_hist = b_client.get_historical_trades(symbol='BNBBTC') #Get Aggregate trades trades_agg = b_client.get_aggregate_trades(symbol='BNBBTC') #Get Kline/Candlesticks candles = b_client.get_klines(symbol='BNBBTC', interval=KLINE_INTERVAL_30MINUTE) #Get 24hr Ticker tickers_24 = b_client.get_ticker() #Get All Prices: Get last price for all markets prices = b_client.get_all_tickers() #Get Orderbook Tickers: Get first bid and ask entry in the order book for all markets tickers_order = b_client.get_orderbook_tickers() ############ # print(h_client.get_orderbook("ETHBTC")) ethbtc_orderbook = h_client.get_orderbook("ETHBTC") #Check to see which coins can be traded and withdrawn h_cryptolist = [] h_currencies = h_client.currencies() for currency in h_currencies: if currency['id'] == 'BTC': print(currency) minimum_ask = 0 minimum_bid = 0 for order, price in ethbtc_orderbook.items(): print(order, ":", price) print(len(price)) # for i in price.length(): if order == 'ask': pass # print("minimum ask price is: ") if order == 'bid': pass
class BnbRestApiClient: def __init__(self): self.client = Client( 'AbEIrslVmOD7sSL4qwEUiuDIsD1DxG7LT9b5ODmMmZemvQotxDaRX1kGzgggwPUu', 'VLXzhtrihiC8nZnB4uZlj1qi3YqN4bGJKjJO8hv4ZULw54BGPPwNBjTPbnhuDg36') def trade_detail(self, symbol, interval): init_data = None handler = ResultHandler(3, symbol) while True: try: if init_data is None: init_data = self.client.get_aggregate_trades( symbol=symbol.upper() + 'USDT', limit=1)[0] while True: time.sleep(10) result = self.client.get_aggregate_trades( symbol=symbol.upper() + 'USDT', fromId=init_data['a']) init_data = result[-1] handler.handle_result(result, interval) except Exception as e: print('币安请求接口异常:{}', e) pass
def get_aggregate_trades_view(request): '''Parameters: symbol (str) – required fromId (str) – ID to get aggregate trades from INCLUSIVE. startTime (int) – Timestamp in ms to get aggregate trades from INCLUSIVE. endTime (int) – Timestamp in ms to get aggregate trades until INCLUSIVE. limit (int) – Default 500; max 500. ''' if request.method == "POST": cli = Client() data = request.data try: agg = cli.get_aggregate_trades(**data) return JsonResponse(agg, safe=False) except BinanceAPIException as e: return JsonResponse({"MessageError": e.message}, safe=False)
def get_aggr_trades(symbol, start_str, end_str, fromID=None): client = Client("", "") output_data = [] limit = 500 start_ts = date_to_milliseconds(start_str) end_ts = date_to_milliseconds(end_str) from_id = None if fromID: from_id = fromID idx = 0 symbol_existed = False while True: temp_data = client.get_aggregate_trades(symbol=symbol, fromId=from_id, limit=limit, startTime=start_ts, endTime=end_ts) if not symbol_existed and len(temp_data): symbol_existed = True if symbol_existed: output_data += temp_data from_id = str(int(temp_data[-1]['a'] + 1)) start_ts = None end_ts = None idx += 1 if temp_data[-1]['T'] > date_to_milliseconds(end_str): temp_data = [ i for i in temp_data if not (i['T'] > date_to_milliseconds(end_str)) ] output_data += temp_data break if idx % 3 == 0: time.sleep(1) return output_data
def call_api_and_save(self, symbol, startTime, endTime, interval, client=False): ## API call if not client: client = Client(api_key, api_secret) aggregated_trades = client.get_aggregate_trades( symbol=symbol, startTime=format_time(startTime), endTime=format_time(endTime), limit=1) ## If there are no trades to be aggregated in this unit of time, saves start and end time and sets price and tstamp to NULL if len(aggregated_trades) == 0: price = None tstamp = None tradeId = None else: aggregated_trades = aggregated_trades[0] price = aggregated_trades['p'] tstamp = aggregated_trades['T'] tradeId = aggregated_trades['a'] data = { 'startTime': startTime, 'endTime': endTime, 'price': price, 'symbol': symbol, 'tstamp': tstamp, 'tradeId': tradeId, 'intvl': interval } ## hours, etc. self.session.add(Aggregated_prices(**data)) self.session.commit() ## Returns client for reuse by a loop making multiple calls to avoid unnecessarily reconnecting return (client)
class market_api(object): def __init__(self): self.client = Client(cfg.api_keys['key'],cfg.api_keys['secret'], {"verify": True, "timeout": 20}) def get_all_orders(self,symbol='VENETH'): return self.client.get_all_orders(symbol=symbol, requests_params={'timeout': 5}) def ping(self): return self.client.ping() def get_system_status(self): return self.client.get_system_status() def get_exchange_info(self): return self.client.get_exchange_info() def get_symbol_info(self,symbol='VENETH'): return self.client.get_symbol_info(symbol=symbol) def get_market_depth(self,symbol='VENETH'): return self.client.get_order_book(symbol=symbol) def get_latest_trades(self,symbol): return self.client.get_recent_trades(symbol=symbol) def get_historical_trades(self,symbol='VENETH'): return self.client.get_historical_trades(symbol=symbol) def get_aggregate_trades(self,symbol='VENETH'): return self.client.get_aggregate_trades(symbol=symbol) def get_tickers(self): return self.client.get_ticker() def get_all_prices(self): return self.client.get_all_tickers() def get_orderbook_tickers(self): return self.client.get_orderbook_tickers()
def get_agg_trades(symbol, start_time=None, end_time=None, fromId=None): #convert user-input datetime string format into UNIX timestamp: if isinstance(start_time, str): start_time = int(dateparser.parse(start_time).timestamp() * 1000) if isinstance(end_time, str): end_time = int(dateparser.parse(end_time).timestamp() * 1000) client = Client() try: result = client.get_aggregate_trades(symbol=symbol, startTime=start_time, endTime=end_time, fromId=fromId) result = pd.DataFrame(result) result = result.rename( columns={ "a": "agg_tradeId", "p": "price", "q": "quantity", "f": "first_tradeId", "l": "last_tradeId", "T": "timestamp", "m": "isBuyerMaker", "M": "isBestMatch" }) result.timestamp = result.timestamp.apply( lambda d: datetime.utcfromtimestamp(d / 1000).strftime( "%Y/%m/%d %H:%M:%S UTC") ) #convert "timestamp" to time string format result = result[[ "timestamp", "agg_tradeId", "price", "quantity", "first_tradeId", "last_tradeId", "isBuyerMaker", "isBestMatch" ]] result.to_csv("/Users/baixiao/Desktop/agg_trades.csv", index=False) except: print( "Error: time between startTime and endTime passed in cannot exceed 1 hour here!!" )
class BinanceAPI: def __init__(self, api_key, api_secret): API_KEY = api_key API_SECRET = api_secret self.client = Client(API_KEY, API_SECRET) def get_ticker(self, pair): try: value = self.client.get_ticker(symbol=pair) return value except Exception as e: print("Exception : " + str(e)) def get_current_price(self, pair): try: ticker = self.client.get_symbol_ticker(symbol=pair) value = ticker["price"] return float(value) except Exception as e: print("Exception : " + str(e)) def get_klines(self, pair, number): try: klines = pd.DataFrame( self.client.get_klines(symbol=pair, interval=Client.KLINE_INTERVAL_30MINUTE, limit=number), columns=[ "OpenTime", "Open", "High", "Low", "Close", "Volume", "CloseTime", "QuoteVolume", "TradeCount", "TakerVolume", "TakerQuoteVolume", "Ignore" ]) value = klines[[ "OpenTime", "Close", "High", "Low", "Volume", "QuoteVolume", "TakerVolume", "TakerQuoteVolume", "TradeCount" ]].copy() value.loc[:, "OpenTime"] = pd.to_datetime(value["OpenTime"].apply( lambda x: datetime.fromtimestamp(int(x / 1000)))) value = value.set_index("OpenTime") return value except Exception as e: print("Exception : " + str(e)) def get_historical_klines(self, pair, start, end): try: klines = pd.DataFrame(self.client.get_historical_klines( start_str=start, end_str=end, symbol=pair, interval=Client.KLINE_INTERVAL_30MINUTE, limit=500), columns=[ "OpenTime", "Open", "High", "Low", "Close", "Volume", "CloseTime", "QuoteVolume", "TradeCount", "TakerVolume", "TakerQuoteVolume", "Ignore" ]) value = klines[[ "OpenTime", "Close", "High", "Low", "Volume", "QuoteVolume", "TakerVolume", "TakerQuoteVolume", "TradeCount" ]].copy() value.loc[:, "OpenTime"] = pd.to_datetime(value["OpenTime"].apply( lambda x: datetime.fromtimestamp(int(x / 1000)))) value = value.set_index("OpenTime") return value except Exception as e: print("Exception : " + str(e)) def get_balance(self, symbol): try: value = self.client.get_asset_balance(asset=symbol) return value except Exception as e: print('Exception : {}'.format(e)) def get_free_balance(self, symbol): try: value = self.client.get_asset_balance(asset=symbol) return float(value["free"]) except Exception as e: print('Exception : {}'.format(e)) def get_futures_balance(self, symbol): try: value = self.client.futures_account_balance() balance = [ balance["balance"] for balance in value if balance["asset"] == symbol ] return float(str(*balance)) except Exception as e: print('Exception : {}'.format(e)) def create_limit_order(self, symbol, price, quantity, side_str): try: if side_str == "BUY": side = self.client.SIDE_BUY elif side_str == "SELL": side = self.client.SIDE_SELL order = self.client.order_limit( symbol=symbol, side=side, timeInForce=self.client.TIME_IN_FORCE_IOC, price=price, quantity=quantity) print(order) print( "buy order created.\nSymbol:{0:5}\nPrice:{1:5}\nQuantity:{2:5}", symbol, price, quantity) except Exception as e: print("Exception : " + str(e)) def create_market_order(self, symbol, quantity, side_str): try: if side_str == "BUY": side = self.client.SIDE_BUY elif side_str == "SELL": side = self.client.SIDE_SELL order = self.client.order_market(symbol=symbol, side=side, quantity=quantity) print(order) print( "buy order created.\nSymbol:{0:5}\nPrice:{1:5}\nQuantity:{2:5}", symbol, price, quantity) except Exception as e: print("Exception : " + str(e)) def create_test_order(self, symbol, quantity, side_str): try: if side_str == "BUY": side = self.client.SIDE_BUY elif side_str == "SELL": side = self.client.SIDE_SELL order = self.client.create_test_order( symbol=symbol, side=side, type=self.client.ORDER_TYPE_MARKET, quantity=quantity) print(order) print("buy order created.\nSymbol:{0:5}\nQuantity:{1:5}".format( symbol, quantity)) except Exception as e: print("Exception : " + str(e)) def create_futures_order(self, symbol, quantity, side_str): try: if side_str == "BUY": side = self.client.SIDE_BUY elif side_str == "SELL": side = self.client.SIDE_SELL order = self.client.futures_create_order( symbol=symbol, side=side, type=self.client.ORDER_TYPE_MARKET, quantity=quantity) #print(order) print("order created.\nSymbol:{0:5}\nQuantity:{1:5}".format( symbol, quantity)) except Exception as e: print("Exception : " + str(e)) def create_futures_stoploss_order(self, symbol, quantity, side_str, price): if side_str == "BUY": side = self.client.SIDE_BUY elif side_str == "SELL": side = self.client.SIDE_SELL order = self.client.futures_create_order(symbol=symbol, stopPrice=price, side=side, type="STOP_MARKET", quantity=quantity) #print(order) #print("order created.\nSymbol:{0:5}\nQuantity:{1:5}".format(symbol,quantity)) def cancel_futures_orders(self, symbol): for i in range(0, 50): try: self.client.futures_cancel_all_open_orders(symbol=symbol) except Exception as e: print("Exception : " + str(e)) continue break def get_open_futures_orders(self, symbol): try: result = self.client.futures_get_open_orders(symbol=symbol) return result except Exception as e: print("Exception : " + str(e)) def get_base_asset(self, symbol): try: return self.client.get_symbol_info(symbol)["baseAsset"] except Exception as e: print("Exception : " + str(e)) def get_quote_asset(self, symbol): try: return self.client.get_symbol_info(symbol)["quoteAsset"] except Exception as e: print("Exception : " + str(e)) def get_all_tickers(self): try: return self.client.get_all_tickers() except Exception as e: print("Exception : " + str(e)) def get_all_orders(self): try: return self.client.get_all_orders() except Exception as e: print("Exception : " + str(e)) def get_trades_data(self, symbol, start, end): try: data = [] value = self.client.get_aggregate_trades(symbol=symbol, startTime=start, endTime=end) value_max = [-float('inf'), -float('inf')] value_min = [float('inf'), float('inf')] #price = self.client.get_historical_klines(start_str = start, end_str = start + 60000, symbol=symbol, interval=Client.KLINE_INTERVAL_1MINUTE, limit=1)[0][1] for i in value: if len(data) == const.IMG_LENGTH: break data.append( [float(i["p"]), float(i["q"]), 0.3 if i["m"] else 0.6]) if len(data) < const.IMG_LENGTH: data += [[0.0, 0.0, 0.0]] * (const.IMG_LENGTH - len(data)) data = data[:const.IMG_LENGTH] data = pd.DataFrame(data) data = (data - data.min()) / (data.max() - data.min()) data = (data - data.mean()) / data.std() data = (data - data.min()) / (data.max() - data.min()) return data.values.tolist() except Exception as e: print("Exception : " + str(e)) data = [] data += [[0.0, 0.0, 0.0]] * (const.IMG_LENGTH) return data
import json from binance.client import Client from service.handler import ResultHandler from binance.websockets import BinanceSocketManager client = Client( 'AbEIrslVmOD7sSL4qwEUiuDIsD1DxG7LT9b5ODmMmZemvQotxDaRX1kGzgggwPUu', 'VLXzhtrihiC8nZnB4uZlj1qi3YqN4bGJKjJO8hv4ZULw54BGPPwNBjTPbnhuDg36') class BnbWssClient: def __init__(self): bm = BinanceSocketManager(client) bm.start_aggtrade_socket('BNBBTC', process_message) bm.start() def process_message(msg): print("message type: {}".format(msg['e'])) print(msg) # do something if __name__ == '__main__': # bm = BinanceSocketManager(client) # bm.start_aggtrade_socket('BNBBTC', process_message) # bm.start() klines = client.get_aggregate_trades(symbol="ethusdt", limit=1) print(json.dumps(klines))
class BotStrategy(object): 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 = {} ''' self.allAggs = [] #Get ALL aggregate trades time = 0 for time in range(time, tlen): self.allAggs.extend(self.client.get_aggregate_trades(symbol=self.pair, startTime=beginag + time * 3600000, endTime=beginag + (time + 1) * 3600000)) self.lastAggIter = 0 #print(self.allAggs) ''' def tick(self, price, chartnumber, high, low, o, t): ############################################# self.price = price self.chartnumber = chartnumber self.high = high self.low = low #nextTrade work nextTrades = [] nextTradeTimes = [] if self.last: #once we get to the latest kline we store current price into next trade vars self.nextTrade = float(price) #nextTradeSeller = float(price) nextTradeTime = 0 else: #testing to see if aggtrades enable/disable works #I'm setting nextTrades to current price so when we buy & sell it should be the same as if there was no nextTrades self.nextTrade = float(price) #nextTradeSeller = float(price) if self.aggTrades: #agtrades = self.client.get_aggregate_trades(symbol=self.pair, startTime=int(t),endTime=int(t) + 14400000) agtrades = self.client.get_aggregate_trades(symbol=self.pair, startTime=int(t), endTime=int(t) + 900000) print("agtrade len", len(agtrades)) print("timestamp for agtrade is ", t) nextTradeSeller = agtrades[0] print(price) print(self.nextTrade) firstNextTrade = float(self.nextTrade['p']) print("FirstNextTrade:", firstNextTrade) print("Kline price:", price) if float(self.nextTrade['p']) == float(price): print("Trade is equal :(") else: print( "Woohoo this means the next trade and not the current price is being used !! :)" ) if not self.aggisNext: counterbro = 1 while self.nextTrade['m']: if counterbro >= len(agtrades): self.nextTrade = agtrades[counterbro - 1] print("There was no buyer that was maker ! ! ! !") break else: self.nextTrade = agtrades[counterbro] counterbro += 1 counterbro = 1 while not nextTradeSeller['m']: if counterbro >= len(agtrades): nextTradeSeller = agtrades[counterbro - 1] print("There was no seller that was maker ! ! !") break else: nextTradeSeller = agtrades[counterbro] counterbro += 1 #get the fraction of nexttrade so we can plot it on x axis print("nextTrade time offset", str(float(self.nextTrade['T']) - t)) #These numbers are hardcoded f**k nextTradeTime = (float(self.nextTrade['T']) - t) / 14400000 nextTradeSeller = float(nextTradeSeller['p']) #print(nextTrade) self.nextTrade = float(self.nextTrade['p']) else: #ADDED THIS WHEN I RETURNED, TRYING TO ABANDON AGGTRADES #GOOD LUCK BRO pass #''' if self.masterDick["ema" + chartnumber] == 0: self.masterDick["ema" + chartnumber] = float(price) self.prevPrevEma = self.prevEma self.prevEma = self.masterDick["ema" + chartnumber] #ema period is 20 self.masterDick["ema" + chartnumber] = self.indicators.expMovingAverage( float(price), 20, self.prevEma) ema = self.masterDick["ema" + chartnumber] #this is the one screwing it up #lengpc = len(self.masterDick["pricechg" + chartnumber]) self.prevPriceChg = self.masterDick["pricechg" + chartnumber] if self.masterDick["count" + chartnumber] > 0: self.masterDick["pricechg" + chartnumber].append( float(price) - self.masterDick["currentPrice" + chartnumber]) pricechg = self.masterDick["pricechg" + chartnumber] if len(pricechg) > self.rsiper: del pricechg[0] self.masterDick["currentPrice" + chartnumber] = float(price) self.prevPrices = self.masterDick["prices" + chartnumber] self.masterDick["prices" + chartnumber].append( self.masterDick["currentPrice" + chartnumber]) prices = self.masterDick["prices" + chartnumber] #stochastic self.prevhighs = self.masterDick["highs" + chartnumber] self.prevlows = self.masterDick["lows" + chartnumber] self.masterDick["highs" + chartnumber].append(high) self.masterDick["lows" + chartnumber].append(low) highs = self.masterDick["highs" + chartnumber] lows = self.masterDick["lows" + chartnumber] if len(highs) > self.stochper: del highs[0] del lows[0] self.prevbigma = self.masterDick["bigma" + chartnumber] self.masterDick["bigma" + chartnumber] = self.indicators.movingAverage( self.masterDick["prices" + chartnumber], 250) self.bigma = self.masterDick["bigma" + chartnumber] self.prevbigmalist = self.masterDick["bigmalist" + chartnumber] self.masterDick["bigmalist" + chartnumber].append( self.masterDick["bigma" + chartnumber]) bigmalist = self.masterDick["bigmalist" + chartnumber] self.prevma15 = self.masterDick["ma15" + chartnumber] self.masterDick["ma15" + chartnumber] = self.indicators.movingAverage( self.masterDick["prices" + chartnumber], 15) self.ma15 = self.masterDick["ma15" + chartnumber] self.prevma15list = self.masterDick["ma15list" + chartnumber] self.masterDick["ma15list" + chartnumber].append( self.masterDick["ma15" + chartnumber]) ma15list = self.masterDick["ma15list" + chartnumber] self.prevma5 = self.masterDick["ma5" + chartnumber] self.masterDick["ma5" + chartnumber] = self.indicators.movingAverage( self.masterDick["prices" + chartnumber], 5) self.ma5 = self.masterDick["ma5" + chartnumber] self.prevma5list = self.masterDick["ma5list" + chartnumber] self.masterDick["ma5list" + chartnumber].append( self.masterDick["ma5" + chartnumber]) ma5list = self.masterDick["ma5list" + chartnumber] ####Bollinger#### #I think using greater than fixed something if (len(self.masterDick["prices" + chartnumber]) > self.bollingerper): self.bolmid = self.indicators.movingAverage( self.masterDick["prices" + chartnumber], self.bollingerper) self.masterDick["bolmid" + chartnumber].append(self.bolmid) self.bolup = self.bolmid + self.indicators.stddev(self.masterDick[ "prices" + chartnumber][(self.bollingerper * -1):]) * 2 self.masterDick["bolup" + chartnumber].append(self.bolup) self.bollow = self.bolmid - self.indicators.stddev(self.masterDick[ "prices" + chartnumber][(self.bollingerper * -1):]) * 2 self.masterDick["bollow" + chartnumber].append(self.bollow) self.bandwidth = (self.bolup - self.bollow) / float(price) * 100 self.masterDick["bandwidth" + chartnumber].append(self.bandwidth) #just untabbed these for reference in graph.listadd boluplist = self.masterDick["bolup" + chartnumber] bollowlist = self.masterDick["bollow" + chartnumber] bolmidlist = self.masterDick["bolmid" + chartnumber] bandwidth = self.masterDick["bandwidth" + chartnumber] #print("Bandwidth:",self.bandwidth) #----rsi start---- #If the data points hit the period of the rsi, start calculating it if self.masterDick["rsifirst" + chartnumber] and (len(pricechg) == self.rsiper): self.masterDick["rsi" + chartnumber] = self.indicators.rsi(pricechg) self.masterDick["pag" + chartnumber] = self.indicators.pag self.masterDick["pal" + chartnumber] = self.indicators.pal print("Ran on iteration", self.masterDick["count" + chartnumber]) self.masterDick["rsilist" + chartnumber].append( self.masterDick["rsi" + chartnumber]) elif not self.masterDick["rsifirst" + chartnumber]: #prev values self.prevrsi = self.masterDick["rsi" + chartnumber] self.prevpag = self.masterDick["pag" + chartnumber] self.prevpal = self.masterDick["pal" + chartnumber] self.masterDick["rsi" + chartnumber] = self.indicators.rsi( pricechg, self.masterDick["pag" + chartnumber], self.masterDick["pal" + chartnumber]) self.masterDick["pag" + chartnumber] = self.indicators.pag self.masterDick["pal" + chartnumber] = self.indicators.pal self.masterDick["rsilist" + chartnumber].append( self.masterDick["rsi" + chartnumber]) rsilist = self.masterDick["rsilist" + chartnumber] rsi = self.masterDick["rsi" + chartnumber] if len(pricechg) == self.rsiper and self.masterDick["rsifirst" + chartnumber]: self.masterDick["rsifirst" + chartnumber] = False print("Falsified rsifirst", self.masterDick["count" + chartnumber], len(pricechg)) #----rsi end---- #----stochastic start---- if len(highs) == self.stochper: #previous values if len(self.masterDick["k" + chartnumber]) > 0: self.prevk = self.masterDick["k" + chartnumber] self.prevfast = self.masterDick["fast" + chartnumber] self.masterDick["k" + chartnumber].append( self.indicators.stochastic(float(price), min(lows), max(highs))) k = self.masterDick["k" + chartnumber] if len(k) > 3: del k[0] self.masterDick["fast" + chartnumber] = self.indicators.movingAverage( k, len(k)) else: k = self.masterDick["k" + chartnumber] fast = self.masterDick["fast" + chartnumber] #----stochastic end---- #Local Maximums and Minimums if len(prices) > 1: lastwasmax = self.indicators.maxes(prices[-3:]) lastwasmin = self.indicators.mins(prices[-3:]) if lastwasmax: lmaxes = self.masterDick["lmaxes" + chartnumber] if lmaxes[0] == -1: lmaxes[0] = self.masterDick["count" + chartnumber] - 1 else: lmaxes.append(self.masterDick["count" + chartnumber] - 1) elif lastwasmin: lmins = self.masterDick["lmins" + chartnumber] if lmins[0] == -1: lmins[0] = self.masterDick["count" + chartnumber] - 1 else: lmins.append(self.masterDick["count" + chartnumber] - 1) self.checkCross(prices[0]) self.masterDick["pchange" + chartnumber] = self.indicators.percentChange( prices, 5) self.masterDick["percentlist" + chartnumber].append( self.masterDick["pchange" + chartnumber]) #setting these to clean up graph.add below lmax = self.masterDick["lmaxes" + chartnumber] lmins = self.masterDick["lmins" + chartnumber] if chartnumber == "1": #Buy/sell #I added +1 so we have the current and previous rsi/stochastic value available. could possibly need to change to +2 if self.masterDick[ "count" + chartnumber] >= self.stochper + 1 and self.masterDick[ "count" + chartnumber] >= self.rsiper + 1: #JUST TOOK OUT EVALUATEPOSITIONS() BECAUSE IT F****N SUCKS PASSING EVERYTHING THROUGH #self.evaluatePositions(price, lows, high, highs, k, o, rsi, chartnumber, t) #self.evaluatePositions(price, nextTrade, lows, high, highs, k, o, rsi, chartnumber, t)#, nextTradeSeller) prices = self.masterDick["prices" + chartnumber] if ((self.masterDick["currentPrice" + chartnumber] < self.ma5) and (self.masterDick["currentPrice" + chartnumber] < self.ma15)): if (self.masterDick["currentPrice" + chartnumber] > prices[-2] or self.masterDick["currentPrice" + chartnumber] == prices[-2]): #print("BUY") pass #you need to make sure the btc in your account matches up with availablebtc #This sets available trading funds (entries) if not self.dentry["placedOrder1" + chartnumber]: for y in range(1, self.entries + 1): self.dentry["buy" + str(y) + chartnumber] = self.availablebase / float( self.entries) #print("vbuy" + str(y),self.dentry["buy" + str(y) + chartnumber]) #trying moving entrycalc outside strats, check history to see if entrycalc is same in each #Most recent - it passed self through as an argument - deleting that self.entrycalc(lows, o) if self.strat > 0: eval(self.stratlist[self.strat]) #putting stoploss check after strat(so it doesn't buy again instantly, REVIEW THIS IN THE FUTURE if self.dentry["placedOrder1" + chartnumber]: self.stoploss() #error check if self.availablebase < 0: print("F**K BITCOIN IS IN THE NEGATIVES-ERROR") print(str(self.availablebase)) if self.graphics: self.graph.add(price, self.ma5, self.ma15, self.bigma, self.masterDick["pchange" + chartnumber], self.masterDick["crossPointA" + chartnumber], self.masterDick["crossPointB" + chartnumber], self.masterDick["crosstime" + chartnumber], self.masterDick["firstcross" + chartnumber], chartnumber, lmax[-1], lmins[-1], ema, rsi, high, low, k, fast, self.nextTrade, self.bolmid, self.bolup, self.bollow, self.bandwidth) #, nextTradeTime) #Since the line between the last two MAcrosses was just graphed, we #change the first point for the next line to the last point of #the current one if (self.masterDick["crosstime" + chartnumber]): self.masterDick["crossPointA" + chartnumber] = self.masterDick["crossPointB" + chartnumber] self.masterDick["crossPointB" + chartnumber] = 0 self.masterDick["firstcross" + chartnumber] = self.masterDick["count" + chartnumber] self.masterDick["crosstime" + chartnumber] = False self.masterDick["count" + chartnumber] += 1 #End of historical klines #DO NOT DELETE, THIS LAUNCHES THE GRAPH #if statement checks if is live and current chart hit the last iteration, self.last if (self.masterDick["count" + chartnumber] == self.chartlen[int(chartnumber) - 1]) and (not self.live): print("so this is the last item in chart" + chartnumber) #total percentage gain availableBasePlaceHolder = 0 if self.dentry["placedOrder1" + chartnumber]: if self.largerpair: availableBasePlaceHolder = self.availablebase + self.amtofalt * float( price) * .999 else: availableBasePlaceHolder = self.availablebase + int( self.amtofalt) * float(price) * .999 else: availableBasePlaceHolder = self.availablebase #percentageee = (availableBasePlaceHolder - self.startbase) * 100 / self.startbase percentageee = (availableBasePlaceHolder - self.startbase) * 100 / self.startbase if self.graphics: self.graph.listadd( ma5list, ma15list, bigmalist, self.masterDick["percentlist" + chartnumber], percentageee, rsilist, chartnumber, boluplist, bollowlist, bolmidlist, bandwidth) #change to if(chartnumber == "1"): print("just ran listadd" + chartnumber) if (self.last): #RETURN################################################^&*&^%$#$%^&*^%$#@$%^&*&^%$# #mas print("mas") #print("ma5",self.prevma5,"ma5list",self.prevma5list,"ma15",self.prevma15,"ma15list",self.prevma15list) #ema print('ema') print("prevEma", self.prevPrevEma, "ema", self.prevEma) #stochastic print('stochastic') print("k", self.prevk, "fast", self.prevfast) print("highs", self.prevhighs, "lows", self.prevlows) #RSI print('rsi') print("rsi", self.prevrsi, "pag", self.prevpag, "pal", self.prevpal) #Timestamps ?????? #if u use this code for liverun, DON'T ACTUALLY SELL if self.dentry["orderPrice1" + self.chartnumber] != 0: self.sell(final=True) print("Started with:", self.startbase, "Ended with:", self.availablebase) print("percent win:", percentageee) print("first entries:", self.totalentries) print("Times the price went up during market order buys:", self.amtofups) for keyz in self.downsnups: print(keyz) sumb = 0 for numb in self.downsnups[keyz]: sumb += numb sumb /= len(self.downsnups[keyz]) print(sumb) print() for poop in range(2, self.entries + 1): print( str(poop) + "entries:", self.dentry["tradeEntries" + str(poop) + chartnumber]) if self.graphics: self.graph.anal() #return data for further analysis #run with a spec strat for marketcomb? #analysis if len(prices) > 1: #add this in if float(price) == prices[-2]: #decide what to do pass #goin down elif float(price) - prices[-2] < 0: if self.upcount != 0: #add shit to dict if str(self.downcount) in self.downsnups: self.downsnups[str(self.downcount)].append( self.upcount) else: self.downsnups[str(self.downcount)] = [self.upcount] self.downcount = 0 self.upcount = 0 self.downcount += 1 #goin up else: #if it hasn't gone down hyet we don't care - decide what to do if price doesnt change above if self.downcount != 0: self.upcount += 1 print(self.downsnups) print("upc", self.upcount) print("downc", self.downcount) ##################### #####END OF TICK##### ##################### def buy(self): price = float(self.price) print("buy") print('avbl BTC:', self.availablebase) self.totalentries += 1 self.dentry["placedOrder1" + self.chartnumber] = True #self.orders["orderPrice" + chartnumber] = self.masterDick["currentPrice" + chartnumber] #######IMPLEMENTING NEXTTRADE #self.dentry["orderPrice1" + chartnumber] = price self.dentry["orderPrice1" + self.chartnumber] = self.nextTrade #if btc to usd, etc if self.largerpair: altbuy = self.dentry["buy1" + self.chartnumber] / self.nextTrade else: #altbuy = int(self.dentry["buy1" + chartnumber] / price) altbuy = int(self.dentry["buy1" + self.chartnumber] / self.nextTrade) #janky way of using nextTrade #Do I need this? already setting altbuy to nextTrade price secondattempt = False if price < self.nextTrade: altbuy = int(altbuy * .9) secondattempt = True self.amtofups += 1 #Hmmmmmm BTCUSDT etc pops this if altbuy * self.nextTrade > self.availablebase: print("ERROR ERROR ERROR ERROR ERROR") #COMBINE THIS TO IF STATEMENT A FEW LINES UP #also idk if will work self.availablebase -= altbuy * self.nextTrade altbuy -= altbuy * .0026 self.amtofalt += altbuy #self.entryprices.append(price) self.entryprices.append(self.nextTrade) print(self.entryprices) if self.graphics: self.graph.buy(self.masterDick["currentPrice" + self.chartnumber], self.masterDick["count" + self.chartnumber], self.chartnumber, 1) print("Fun:", self.amtofalt) print("Buy1", self.dentry["buy1" + self.chartnumber]) print("NextPrice:", self.nextTrade) if secondattempt: print("On second attempt") else: print("On first attempt") def sell(self, final=False, stopped=False): price = float(self.price) self.dentry["placedOrder1" + self.chartnumber] = False self.dentry["orderGain1" + self.chartnumber] = ( (self.masterDick["currentPrice" + self.chartnumber] - self.dentry["orderPrice1" + self.chartnumber]) / self.dentry["orderPrice1" + self.chartnumber]) * 100 self.dentry["orderGain1" + self.chartnumber] = self.dentry["orderGain1" + self.chartnumber] / float( self.entries) for x in range(2, self.entries + 1): if self.dentry["placedOrder" + str(x) + self.chartnumber]: self.dentry["placedOrder" + str(x) + self.chartnumber] = False self.dentry["orderGain" + str(x) + self.chartnumber] = ( (self.masterDick["currentPrice" + self.chartnumber] - self.dentry["orderPrice" + str(x) + self.chartnumber]) / self.dentry["orderPrice" + str(x) + self.chartnumber]) * 100 self.dentry["orderGain" + str(x) + self.chartnumber] = self.dentry["orderGain" + str( x) + self.chartnumber] / float(self.entries) #may or may not work if self.largerpair: self.availablebase += self.amtofalt * price * .9984 self.amtofalt -= self.amtofalt else: #self.availablebase += int(self.amtofalt) * nextTradeSeller self.availablebase += int(self.amtofalt) * price * .9984 self.amtofalt -= int(self.amtofalt) if self.graphics and not final: self.graph.sell(self.masterDick["currentPrice" + self.chartnumber], self.masterDick["count" + self.chartnumber], self.dentry["orderGain1" + self.chartnumber], self.chartnumber, stopped) print("sell", self.price) print("NextPrice:", self.nextTrade) print("BTC:", self.availablebase) #this gon f**k it up self.entryprices = [] def stoploss(self): """ Gets out of the buy if price dips below predetermined percent """ price = float(self.price) print("orderPrice1:", self.dentry["orderPrice1" + self.chartnumber]) if (self.dentry["orderPrice1" + self.chartnumber] - price ) / self.dentry["orderPrice1" + self.chartnumber] * 100 >= self.stopPercent: self.sell(stopped=True) def entrycalc(self, lows, o): """ I think this has something to do with how many times you go in, might wanna leave it to the strats """ price = float(self.price) #print(nextTrade==price,nextTradeSeller==price) for i in range(2, self.entries + 1): if len(self.entryprices) > 0: avgentryprice = sum(self.entryprices) / len(self.entryprices) #if previous entry has been placed and current hasn't and other args are met if self.dentry[ "placedOrder" + str(i - 1) + self.chartnumber] and price < avgentryprice and float( price) < lows[-2] and float(price) < float( o) and not self.dentry["placedOrder" + str(i) + self.chartnumber]: self.dentry["placedOrder" + str(i) + self.chartnumber] = True #add these to dict print("trade number", str(i)) self.dentry["tradeEntries" + str(i) + self.chartnumber] += 1 #self.totalentries += 1 #I changed these from price to nextTrade self.dentry["orderPrice" + str(i) + self.chartnumber] = price #self.dentry["orderPrice" + str(i) + chartnumber] = self.nextTrade #altbuy = int(self.dentry["buy" + str(i) + chartnumber] / price) altbuy = int( self.dentry["buy" + str(i) + self.chartnumber] / self.nextTrade) #self.availablebase -= altbuy * price self.availablebase -= altbuy * self.nextTrade altbuy -= altbuy * .001 self.amtofalt += altbuy ###HOW LONG TO WE WANT ENTRYPRICES TO BE?? #self.entryprices.append(price) self.entryprices.append(self.nextTrade) if self.graphics: self.graph.buy( self.masterDick["currentPrice" + self.chartnumber], self.masterDick["count" + self.chartnumber], self.chartnumber, i) #print("Fun:",self.amtofalt) print("Buy" + str(i), self.dentry["buy" + str(i) + self.chartnumber]) break def checkCross(self, price): #if moving avgs cross if (self.masterDick["count" + self.chartnumber] > 0): ma5list = self.masterDick["ma5list" + self.chartnumber] ma15list = self.masterDick["ma15list" + self.chartnumber] self.masterDick["ma5lower" + self.chartnumber] = ma15list[ -2] <= ma5list[-2] and ma15list[-1] > ma5list[-1] self.masterDick["ma5higher" + self.chartnumber] = ma15list[ -2] >= ma5list[-2] and ma15list[-1] < ma5list[-1] #This buys or sells due to a cross in the MAs, you'll want to #move this out of this if statement eventually bcoz it will #evaluate other factors as well #self.evaluatePositions(chartnumber) if (self.masterDick["ma5lower" + self.chartnumber] or self.masterDick["ma5higher" + self.chartnumber]): self.masterDick[ "crossPointA" + self.chartnumber], self.masterDick[ "crossPointB" + self.chartnumber] = self.indicators.MACross( ma5list[-2:], ma15list[-2:], self.masterDick["crossPointA" + self.chartnumber], price) self.masterDick["crosstime" + self.chartnumber] = True #evaluate the position of a chart only when it's gained an item. use smaller chart changes #to influence current buys in the bigger charts ''' def evaluatePositions(self, price, nextTrade, lows, high, highs, k, o, rsi, chartnumber, t, nextTradeSeller=None): prices = self.masterDick["prices" + chartnumber] if((self.masterDick["currentPrice" + chartnumber] < self.ma5) and (self.masterDick["currentPrice" + chartnumber] < self.ma15)): if(self.masterDick["currentPrice" + chartnumber] > prices[-2] or self.masterDick["currentPrice" + chartnumber] == prices[-2]): #print("BUY") pass #you need to make sure the btc in your account matches up with availablebtc #could have rounding errors and say you have more than you actually do, shouldn't be significant tho- #especially if you check your bitcoin funds after every sell if not self.dentry["placedOrder1" + chartnumber]: for y in range(1, self.entries + 1): self.dentry["buy" + str(y) + chartnumber] = self.availablebase / float(self.entries) #print("vbuy" + str(y),self.dentry["buy" + str(y) + chartnumber]) #trying moving entrycalc outside strats, check history to see if entrycalc is same in each self.entrycalc(self, price, chartnumber, nextTrade, lows, o) if self.strat > 0: eval(self.stratlist[self.strat]) #error check if self.availablebase < 0: print("F**K BITCOIN IS IN THE NEGATIVES-ERROR") print(str(self.availablebase)) ''' ######Strategies######################################################## #THIS ONE IS F*****G GREAT FOR FUNBTC def firstone(self, lows, highs, k, o): #, nextTradeSeller): price = float(self.price) prices = self.masterDick["prices" + self.chartnumber] #self.entrycalc(price, chartnumber, nextTrade, lows, o) #buy/sell #need 2 change stochastic #just added rsi for testing #print(self.price,self.dentry["orderPrice1" + self.chartnumber]) #print(type(self.dentry["orderPrice1" + self.chartnumber]), "butt") if price < prices[-2] and prices[-2] < prices[ -3] and self.high < highs[-2] and k[-1] < self.masterDick[ "fast" + self.chartnumber] and not self.dentry[ "placedOrder1" + self.chartnumber]: # and rsi < 50: self.buy() elif price > self.ma15 and price > highs[-2] and self.dentry[ "placedOrder1" + self. chartnumber]: # and (self.dentry["orderPrice1" + self.chartnumber] * 1.001 < price * 1.001 or price < self.bigma): self.sell() ############################################################################################################## ############################################################################################################## def secondone(self, lows, highs, k, o): price = float(self.price) prices = self.masterDick["prices" + self.chartnumber] #self.entrycalc(price, chartnumber, nextTrade, lows, o) #buy/sell #need 2 change stochastic #just added rsi for testing if price < prices[-2] and prices[-2] < prices[-3] and prices[ -3] < prices[-4] and self.high < highs[-2] and k[ -1] < self.masterDick[ "fast" + self.chartnumber] and not self.dentry[ "placedOrder1" + self.chartnumber]: # and rsi < 50: self.buy() elif price > self.ma15 and price > highs[-2] and self.dentry[ "placedOrder1" + self.chartnumber]: self.sell() #BTCUSDT on 12 hour interval def thirdone(self): #setting vars to simple names to reduce clutter price = float(self.price) rsi = self.masterDick["rsi" + self.chartnumber] #could do this or put something in botIndicators to check? - Maybe not if len(self.masterDick["prices" + self.chartnumber]) > self.bollingerper + 2: bws = self.masterDick["bandwidth" + self.chartnumber] if self.bandwidth < 14 and price > self.bolup and not self.dentry[ "placedOrder1" + self.chartnumber]: self.buy() #bandwidth less than last one AND rsi/stoch calmed down AND price is greater or smaller than last one elif self.bandwidth < bws[-2] and rsi > 50 and self.dentry[ "placedOrder1" + self.chartnumber]: self.sell()
initialEth = 0.05 f = open("Trades.txt", "w+") f.close() buyC = '' sellPrice = 0.0 while True: if tradedCoin == 'ETH': buyC = screen() if buyC == '': t = strftime("%Y-%m-%d %H:%M:%S", localtime()) f = open("Trades.txt", "a") f.write('At ' + t + ' Could not find anything\n') f.close() else: trade = client.get_aggregate_trades(symbol=buyC) tradedVol = etherVol / float(trade[-1]['p']) print(wallet) wallet.at[buyC[:-3], 'balance'] = etherVol / float(trade[-1]['p']) print(wallet) tradedCoin = buyC[:-3] etherVol = 0.0 t = strftime("%Y-%m-%d %H:%M:%S", localtime()) f = open("Trades.txt", "a") f.write('At ' + t + ' ' + str(tradedVol) + ' ' + buyC[:-3] + ' bought at ' + trade[-1]['p'] + '.\n') f.close() sellPrice = float(trade[-1]['p']) * 1.001 else: trade = client.get_aggregate_trades(symbol=buyC) if float(trade[-1]['p']) >= sellPrice:
from binance.client import Client import json import pandas as pd client = Client( api_key='uaEbKoKxuheh8iDUJ00DuIhXAFP8SUFy4OSi1vI05p5waDhDFgn26N1x7Dk0npvq', api_secret= 'kubPstz31X8ypBggaABpbywNqQV7mOdKMu5eLriOAnie3BS841mVmiRX0IhLRizZ') orderbook = client.get_order_book(symbol='BNBBTC') traders = client.get_aggregate_trades(symbol='BNBBTC') candle = client.get_klines(symbol='BNBBTC', interval='1h') # transform orderbook to dataframe df1 = pd.DataFrame(orderbook) df_bid = pd.DataFrame(orderbook['bids']) df_bid.columns = ['bid_price', 'bid_QTY'] df_ask = pd.DataFrame(orderbook['asks']) df_ask.columns = ['ask_price', 'ask_QTY'] df_id = df1['lastUpdateId'] df_orderbook = pd.concat([df_ask, df_bid], axis=1) df_orderbook = pd.concat([df_id, df_orderbook], axis=1) print(df_orderbook.head()) # df_orderbook.to_csv('orderbook.csv') # transform traders to dataframe df_traders = pd.DataFrame(traders) df_traders.columns = [ 'Aggregated TradeId', 'Price', 'Quantity', 'First TradeId', 'Last TradeId', 'Timestamp', 'Was the buyer the maker?', 'Was the trade the best price match?' ]
class trade_realtime(): def __init__(self, api_key, api_secret, total_list=None): self.coin_list = total_list self.api_key = api_key self.api_secret = api_secret self.client = Client(api_key, api_secret) def get_time(self): server_time = self.client.get_server_time() # { # "serverTime": 1499827319559 # } return int(server_time['serverTime']) def get_exchange_status(self): return self.client.get_system_status() def get_coin_price(self, coin_list): # kwargs = {'data': coin} output_data = [] for coin in coin_list: price_d = ast.literal_eval( json.dumps(self.client.get_symbol_ticker(symbol=coin))) print(price_d) price = float(price_d['price']) output_data.append(price) return output_data def get_trade(self, start, end): output_data = [] for coin in self.coin_list: output_data.append( self.client.get_aggregate_trades(symbol=coin, startTime=start, endTime=end)) return output_data def get_kline(self, start, end): output_data = [] for coin in self.coin_list: output_data.append( self.client.get_klines(symbol=coin, interval=Client.KLINE_INTERVAL_5MINUTE, limit=500, startTime=start, endTime=end)) return output_data def get_historical_klines(self, symbol, interval, start, end): # init our list output_data = [] # setup the max limit limit = 500 timeframe = interval_to_milliseconds(interval) start_ts = start idx = 0 # it can be difficult to know when a symbol was listed on Binance so allow start time to be before list date symbol_existed = False while True: # fetch the klines from start_ts up to max 500 entries or the end_ts if set temp_data = self.client.get_klines(symbol=symbol, interval=interval, limit=limit, startTime=start_ts, endTime=end) # handle the case where our start date is before the symbol pair listed on Binance if not symbol_existed and len(temp_data): symbol_existed = True if symbol_existed: # append this loops data to our output data output_data += temp_data # update our start timestamp using the last value in the array and add the interval timeframe start_ts = temp_data[len(temp_data) - 1][0] + timeframe else: # it wasn't listed yet, increment our start date start_ts += timeframe idx += 1 # check if we received less than the required limit and exit the loop if len(temp_data) < limit: # exit the while loop break # sleep after every 3rd call to be kind to the API if idx % 3 == 0: time.sleep(1) return output_data def get_orderbook_ticker(self): pass def order_limit_buy(self, **params): return self.client.order_limit_buy(**params) def order_limit_sell(self, **params): return self.client.order_limit_sell(**params) def order_market_sell(self, **params): return self.client.order_market_sell(**params) def order_market_buy(self, **params): return self.client.order_market_buy(**params) def get_open_orders(self, **params): return self.client.get_open_orders(**params) def create_test_order(self, **params): self.client.create_test_order() def get_order(self, **params): self.client.get_order(self, **params) def get_all_orders(self, **params): self.client.get_all_orders(self, **params) def cancel_order(self, **params): self.client.cancel_order(self, **params) def get_account(self, **params): return (self.client.get_account(recvWindow=self.get_time())) def get_asset_balance(self, asset, **params): bal = self.client.get_asset_balance(asset=asset, recvWindow=self.get_time()) return ast.literal_eval(json.dumps(bal))['free'] def start_trade(): pass def get_kline_lag_time(self, coin, lookback_in_ms): # lookback = 2*60*1000 #5mins # rt.pred_coin_list=[coin] end_ts = self.get_time() # calendar.timegm(time.gmtime()) -lookback start_ts = end_ts - lookback_in_ms # print("start=",start_ts) # print("end=",end_ts) f = self.get_historical_klines(symbol=coin, interval=Client.KLINE_INTERVAL_30MINUTE, end=end_ts, start=start_ts) f = ast.literal_eval(json.dumps(f)) return f def getState(self, coin_list): features = np.empty((LOOK_BACK, 0), float) coin_f_index = [2, 3, 4, 5, 7] for coin in coin_list: coin_f = np.array(self.get_kline_lag_time(coin, LOOK_BACK_IN_MS), dtype=np.float).reshape(-1, 12) coin_f = coin_f[coin_f.shape[0] - LOOK_BACK:, coin_f_index] if (coin_f.shape[0] < 10): print("something is wrong with binance api,return shape=", coin_f.shape) return #print("coin_f shape ",coin_f.shape) #print("features shape ",features.shape) # COIN_FEATURE = np.concatenate((COIN_FEATURE, tmp), axis=0) features = np.hstack((features, coin_f)) # features = self.create_input(features,LOOK_BACK) # DF_FEATURES #reshape for tensorflow backend features = features.reshape(1, DF_FEATURES, 1, LOOK_BACK) print("create_predictive_input, features shape ", features.shape) # print("kline shape after modify",features.shape) # features = self.create_input(features ,LOOK_BACK) return features
for i in prices: total += float(i['p']) return total / len(prices) client = Client(api_key, api_secret) try: coin1, coin2 = input( 'Enter coins to trade(Default: BNB USDT ): ').upper().split() except: coin1 = 'BNB' coin2 = 'USDT' try: coin = coin1 + coin2 prices = client.get_aggregate_trades(symbol=coin) buy = coin1 sell = coin2 except: coin = coin2 + coin1 prices = client.get_aggregate_trades(symbol=coin) buy = coin2 sell = coin1 print("Current average price of", coin, "is", average_price(prices)) print("Last price of", coin, "is", prices[-1]['p']) profit = 0 while profit <= 0.2: choice = input( 'Buying and selling price should differ by 0.2% atleast...hit enter to continue' ) if choice == "":
class BinanceOperator(ExchangeOperator): """Used to directly operate with the Binance exchange api. Has all relevant api methods in their raw form. """ def __init__(self): """Initialize BinanceOperator with api credentials.""" client_id, client_secret = creds[0], creds[1] self.client = Client(client_id, client_secret) def get_market_depth(self, symbol): depth = self.client.get_order_book(symbol=symbol) return depth def get_recent_trades(self, symbol): trades = self.client.get_recent_trades(symbol=symbol) return trades def get_historical_trades(self, symbol): trades = self.client.get_historical_trades(symbol=symbol) return trades def get_aggregate_trades(self, symbol): trades = self.client.get_aggregate_trades(symbol=symbol) return trades def get_24hr_tickers(self): tickers = self.client.get_ticker() return tickers def get_symbol_info(self, symbol): info = self.client.get_symbol_info(symbol) return info def get_candlesticks(self, symbol, interval): candles = self.client.get_klines(symbol=symbol, interval=interval) return candles """ Candlestick data response from Binance is in the following format: [ [ 1499040000000, // Open time "0.01634790", // Open "0.80000000", // High "0.01575800", // Low "0.01577100", // Close "148976.11427815", // Volume 1499644799999, // Close time "2434.19055334", // Quote asset volume 308, // Number of trades "1756.87402397", // Taker buy base asset volume "28.46694368", // Taker buy quote asset volume "17928899.62484339" // Ignore. ] ] """ def get_historical_candlesticks(self, symbol, interval, start_time, end_time=None): """Returns candlestick data in the form ['time', 'open', 'high', 'low', 'close', 'volume'] """ if end_time is None: candles = self.client.get_historical_klines( symbol, interval, start_time) else: candles = self.client.get_historical_klines( symbol, interval, start_time, end_time) data_df = pd.DataFrame(candles, columns=[ 'time', 'open', 'high', 'low', 'close', 'volume', 'close_time', 'quote_asset_volume', 'num_trades', 'tkbbav', 'tkqav', 'ign.' ]) data_df = data_df[['time', 'open', 'high', 'low', 'close', 'volume']] # Convert all numbers from str to float data_df = type_format_df(data_df, float) return data_df def get_account_info(self): return self.client.get_account() def get_asset_balance(self, asset): return self.client.get_asset_balance(asset=asset) def get_trade_fees(self): return self.client.get_trade_fee()
class StreamlitView(): is_executed_golden_cross = False def __init__(self, time_scale, will_be_taken=None): self.TRADE_SYMBOL = "SUPERUSDT" self.time_scale = time_scale self.client = Client(config.API_KEY, config.API_SECRET) self.get_candle_data() self.money = 500 self.amount = 0 self.will_be_taken = will_be_taken self.winners = [] @property def get_supertrend(self): atr_period, atr_multiplier = 10, 2 try: atr = talib.ATR(self.high, self.low, self.close, atr_period) except: return False, False previous_final_upperband = 0 previous_final_lowerband = 0 final_upperband = 0 final_lowerband = 0 previous_close = 0 previous_supertrend = 0 supertrend = [] supertrendc = 0 for i in range(0, len(self.close)): if np.isnan(self.close[i]): pass else: highc = self.high[i] lowc = self.low[i] atrc = atr[i] closec = self.close[i] if math.isnan(atrc): atrc = 0 basic_upperband = (highc + lowc) / 2 + atr_multiplier * atrc basic_lowerband = (highc + lowc) / 2 - atr_multiplier * atrc if basic_upperband < previous_final_upperband or previous_close > previous_final_upperband: final_upperband = basic_upperband else: final_upperband = previous_final_upperband if basic_lowerband > previous_final_lowerband or previous_close < previous_final_lowerband: final_lowerband = basic_lowerband else: final_lowerband = previous_final_lowerband if previous_supertrend == previous_final_upperband and closec <= final_upperband: supertrendc = final_upperband else: if previous_supertrend == previous_final_upperband and closec >= final_upperband: supertrendc = final_lowerband else: if previous_supertrend == previous_final_lowerband and closec >= final_lowerband: supertrendc = final_lowerband elif previous_supertrend == previous_final_lowerband and closec <= final_lowerband: supertrendc = final_upperband supertrend.append(supertrendc) previous_close = closec previous_final_upperband = final_upperband previous_final_lowerband = final_lowerband previous_supertrend = supertrendc return supertrend @property def get_rsi(self): rsi = talib.RSI(self.close, RSI_PERİOD) return rsi @property def get_stokrsi(self): rsi = self.get_rsi(self.close) stochrsif, stochrsis = talib.STOCH(rsi, rsi, rsi, fastk_period=14, slowk_period=3, slowd_period=3) return stochrsif, stochrsis @property def get_bband(self): uband, mband, lband = talib.BBANDS(self.close) return uband, mband, lband @property def get_ema(self): # ema = talib.EMA(self.close) ema = talib.EMA(self.close) return ema @property def candle_chart(self, trade_symbol=None): if trade_symbol: candle_chart = go.Figure( data=go.Candlestick(x=self.tarih, close=self.close, open=self.acilis, high=self.high, low=self.low, name=self.TRADE_SYMBOL)) return candle_chart else: candle_chart = go.Figure( data=go.Candlestick(x=self.tarih, close=self.close, open=self.acilis, high=self.high, low=self.low, name=self.TRADE_SYMBOL)) return candle_chart @property def get_macd(self): macd, macdsignal, macdhist = talib.MACD(self.close, fastperiod=12, slowperiod=26, signalperiod=9) return macd, macdsignal, macdhist def candles(self, trade_symbol=None): if trade_symbol: candless = self.client.get_klines(symbol=trade_symbol, interval=self.time_scale) return candless else: candless = self.client.get_klines(symbol=self.TRADE_SYMBOL, interval=self.time_scale) return candless def get_triple_ma(self, close=None): if close is not None: seventeen = talib.MA(close, 17) fifty = talib.MA(close, 50) hundred = talib.MA(close, 200) return seventeen, fifty, hundred else: seventeen = talib.MA(self.close, 17) fifty = talib.MA(self.close, 50) hundred = talib.MA(self.close, 200) return seventeen, fifty, hundred @staticmethod def control_key_in_gi(name): if name in gi.keys(): return gi[name]["name"], gi[name]["type"] else: raise KeyError( "Girdiğiniz 'indikatör_name' parametresi 'self.signals' fonksiyonunda bulunmuyor." ) @staticmethod def page_config(): st.set_page_config( page_title="Ex-stream-ly Cool App", page_icon="🧊", layout="centered", initial_sidebar_state="auto", ) StreamlitView.view_side_bar() st.title("My Binance Trading Bot") @staticmethod def candles_to_df(candles): candle_df = pd.DataFrame(candles) candle_df.columns = [ "AcilisZamani", "Acilis", "EnYuksek", "EnDusuk", "Kapanis", "Volume", "KapanisZamani", "QuoteAssetVolume", "NumberOfTrades", "TakerBuyBaseAssetVolume", "TakerBuyQuoteAssetVolume", "Ignore" ] return candle_df @staticmethod def view_side_bar(): add_selectbox = st.sidebar.selectbox( "Lütfen bir sekme seçin.", ("Twitter", "Kripto Para Analizi", "Coindesk", "Coinbase")) return add_selectbox def get_news_from_marketcal(self): url = "https://developers.coinmarketcal.com/v1/events" querystring = {"max": "10", "coins": "terra-virtua-kolect"} payload = "" headers = { 'x-api-key': config.MARKET_CAL_API_KEY, 'Accept-Encoding': "deflate, gzip", 'Accept': "application/json" } response = requests.request("GET", url, data=payload, headers=headers, params=querystring) # response = requests.request("GET", url, headers=headers) print(response.text) def get_candle_data(self, last_price=False, testing_number: int = -1, df=None): if df is not None: close = df["Kapanis"].values[:testing_number].astype(np.float64) high = df["EnYuksek"].values[:testing_number].astype(np.float64) low = df["EnDusuk"].values[:testing_number].astype(np.float64) acilis = df["Acilis"].values[:testing_number].astype(np.float64) if testing_number != -1: self.tarih = df["AcilisZamani"].apply( lambda x: datetime.fromtimestamp( x / 1e3)).values[:testing_number + 1] if testing_number == -1: tarih = df["AcilisZamani"].apply( lambda x: datetime.fromtimestamp(x / 1e3))[:-1] return tarih, acilis, close, high, low else: df = self.candles_to_df(self.candles()) if last_price: return float(df["Kapanis"].values[:testing_number][-1]) else: self.close = df["Kapanis"].values[:testing_number].astype( np.float64) self.high = df["EnYuksek"].values[:testing_number].astype( np.float64) self.low = df["EnDusuk"].values[:testing_number].astype( np.float64) self.acilis = df["Acilis"].values[:testing_number].astype( np.float64) if testing_number != -1: self.tarih = df["AcilisZamani"].apply( lambda x: datetime.fromtimestamp( x / 1e3)).values[:testing_number + 1] if testing_number == -1: self.tarih = df["AcilisZamani"].apply( lambda x: datetime.fromtimestamp(x / 1e3))[:-1] return self.tarih, self.acilis, self.close, self.high, self.low def signal_to_text(self, indicator_name, signal): prettyname, type = self.control_key_in_gi(indicator_name) if signal == 1: message = f":dollar::moneybag: {prettyname} {type} **Al sinyali üretiyor**." st.info(message) return message elif signal == 2: message = f":dollar::moneybag: {prettyname} {type} **Sat sinyali üretiyor**." st.success(message) return message else: message = f":pensive: Üzgünüm **almak veya satmak için biraz daha beklemelisin** {prettyname} {type} **net bir sinyal üretmiyor**." st.info(message) return message def lastprev_close_indicator(self, indicator_results): last_close = self.close[-1] previous_close = self.close[-2] last_indicator_result = indicator_results[-1] previous_indicator_result = indicator_results[-2] return last_close, previous_close, last_indicator_result, previous_indicator_result def signals(self, indicator_name, print_signal=True, closes=None): """ ! RETURN 1 al sinyali ! RETURN 2 sat sinyali ! RETURN False hiçbirşey yapma sinyali ! Closes Golden cross bulmak için kullanılır. Her coinin kapanislari aynı olmadığından dolayı kapanislar dışarıdan verilir. ! print_signal parametresi Golden cross ararken ekrana boş yere sinyal yazılmasın diye konulmuştur. """ self.control_key_in_gi(indicator_name) if indicator_name == "supertrend": lc, pc, lic, pic = self.lastprev_close_indicator( indicator_results=self.get_supertrend) # Trend yeni döndüyse son 3 kapanışta döndüyse # Alım Sinyali ispclowest = list(filter(lambda x: x < pc, self.close[-3:])) # Satış Sinyali ispichighest = list(filter(lambda x: x > pic, self.close[-3:])) if lc > lic and len(ispclowest) >= 1: result = 1 elif lc < lic and len(ispichighest) >= 1: result = 2 else: result = False elif indicator_name == "rsi": last_rsi = self.get_rsi[-1] if last_rsi <= 20: result = 1 elif last_rsi > 80: result = 2 else: result = False elif indicator_name == "macd": macd, macdsignal, macdhist = self.get_macd last_macd = macd[-1] last_macd_signal = macdsignal[-1] previous_macd = macd[-2] previous_macd_signal = macdsignal[-2] macd_cross_up = last_macd > last_macd_signal and previous_macd < previous_macd_signal if macd_cross_up: result = 1 else: result = False elif indicator_name == "ema": last_ema = self.get_ema[-1] last_close = self.close[-1] if last_close < (last_close - last_close * 0.05): result = 1 elif last_close > (last_ema + last_ema * 0.05): result = 2 else: result = False elif indicator_name == "bband": uband, mband, lband = self.get_bband last_uband = uband[-1] last_lband = lband[-1] last_close = self.close[-1] if last_lband > last_close: result = 1 elif last_uband < last_close: result = 2 else: result = False elif indicator_name == "tripleMA": if closes is not None: seventeen, fifty, hundred2 = self.get_triple_ma(closes) last_seventeen = seventeen[-1] prev_seventeen = seventeen[-2] lastfifty = fifty[-1] previousfifty = fifty[-2] lasthundred2 = hundred2[-1] previoushundred2 = hundred2[-2] else: seventeen, fifty, hundred2 = self.get_triple_ma() last_seventeen = seventeen[-1] prev_seventeen = seventeen[-2] lastfifty = fifty[-1] previousfifty = fifty[-2] lasthundred2 = hundred2[-1] previoushundred2 = hundred2[-2] # MA-50 MA-200 ü keserse # if previousfifty < previoushundred2 and lastfifty > lasthundred2: # result = 1 last_three_period = hundred2[-4:] is_signal = False for index, i in enumerate(last_three_period): if -len(last_three_period) + index + 1 == 0: break if i > seventeen[-len(last_three_period) + index] and i < seventeen[ -len(last_three_period) + index + 1]: print(i, seventeen[-len(last_three_period) + index]) print(i, seventeen[-len(last_three_period) + index + 1]) print(is_signal) print("\n" * 2) is_signal = True if is_signal: result = 1 elif previousfifty > previoushundred2 and lastfifty < lasthundred2: result = 2 else: result = False if print_signal: self.signal_to_text(indicator_name=indicator_name, signal=result) return result def get_prices_from_symbol(self, symbol): theta_price = self.client.get_aggregate_trades(symbol=symbol) return theta_price[-1]["p"] def ask_symbol(self): symbol = st.text_input( label="Piyasa Değerini Öğrenmek İçin Sembol Giriniz", value="", max_chars=10, key=None, type='default') if symbol and symbol.upper() != self.TRADE_SYMBOL: self.TRADE_SYMBOL = symbol.upper() self.get_candle_data() try: st.write( f"**{symbol.upper()}** piyasa değeri **{self.get_prices_from_symbol(symbol=symbol.upper())}**" ) except Exception as e: raise Exception("Üzgünüz Böyle Bir Sembol Bulamadık.") def supertrend_chart(self): super_trend_fig = self.candle_chart super_trend_fig.add_trace( go.Scatter(x=self.tarih, y=self.get_supertrend, name='SuperTrend')) return super_trend_fig def rsi_chart(self): rsi = self.get_rsi data = {"rsi": rsi, "tarih": self.tarih} df = pd.DataFrame(data=data) fig = px.line(df, x="tarih", y="rsi") return fig def ema_chart(self): ema = self.get_ema ema_fig = self.candle_chart ema_fig.add_trace( go.Scatter(x=self.tarih, y=ema, name='EMA', line=go.scatter.Line(color="black"))) return ema_fig def triple_ma_chart(self): seventeen, fifty, hundred = self.get_triple_ma() fig = self.candle_chart fig.add_trace( go.Scatter(x=self.tarih, y=seventeen, name='17', line=go.scatter.Line(color="orange"))) fig.add_trace( go.Scatter(x=self.tarih, y=fifty, name='50', line=go.scatter.Line(color="purple"))) fig.add_trace( go.Scatter(x=self.tarih, y=hundred, name='100', line=go.scatter.Line(color="blue"))) return fig def bband_chart(self): uband, mband, lband = self.get_bband bband_fig = self.candle_chart bband_fig.add_trace( go.Scatter(x=self.tarih, y=uband, name='Upper-Band', line=go.scatter.Line(color="black"))) bband_fig.add_trace( go.Scatter(x=self.tarih, y=mband, name='Middle-Band', line=go.scatter.Line(color="black"))) bband_fig.add_trace( go.Scatter(x=self.tarih, y=lband, name='Lower-Band', line=go.scatter.Line(color="black"))) return bband_fig def macd_chart(self): macd = self.get_macd self.signals("macd", macd) def generate_fig(self): pass def show_chart(self, name): prettyname, type = self.control_key_in_gi(name) signal = None if name == "candlestick": st.subheader(f"{self.TRADE_SYMBOL} {prettyname} {type}") st.plotly_chart(self.candle_chart) elif name == "supertrend": st.subheader(f"{prettyname} {type}") st.plotly_chart(self.supertrend_chart()) signal = self.signals(indicator_name="supertrend") elif name == "rsi": st.subheader(f"{prettyname} {type}") st.plotly_chart(self.rsi_chart()) signal = self.signals("rsi") elif name == "bband": st.subheader(f"{prettyname} {type}") st.plotly_chart(self.bband_chart()) signal = self.signals("bband") elif name == "ema": st.subheader(f"{prettyname} {type}") st.plotly_chart(self.ema_chart()) signal = self.signals("ema") elif name == "stokrsi": pass elif name == "macd": pass elif name == "tripleMA": st.subheader(f"{prettyname} {type}") st.plotly_chart(self.triple_ma_chart()) signal = self.signals("tripleMA") else: st.subheader(f"{prettyname} {type}") return signal def show_orderbook(self): tickers = self.client.get_order_book(symbol=self.TRADE_SYMBOL) df = pd.DataFrame(tickers) print(df) def buy(self, testing_number): if self.money >= 500: lp = self.get_candle_data(last_price=True, testing_number=testing_number) self.amount = self.money / lp self.money = 0 def sell(self, testing_number): if self.amount: lp = self.get_candle_data(last_price=True, testing_number=testing_number) st.write(lp) self.money = self.money + self.amount * lp self.amount = 0 def show_wallet(self): print(f"Cüzdanınızda bulunan para miktarı {self.money} $") print( f"Cüzdanınızda bulunan {self.TRADE_SYMBOL}, {self.amount} kadardır." ) def testing(self): # ma perioddan dolayı for i in range(200, 500): self.get_candle_data(testing_number=i) # self.view_side_bar() # self.ask_symbol() # self.show_chart("candlestick") lp = self.get_candle_data(last_price=True, testing_number=i) st.write(lp) s1 = self.signals("supertrend") s2 = self.signals("rsi") # s3 = self.signals("bband") # s4 = self.signals("ema") s5 = self.signals("tripleMA") signals = [s1, s2, s5] buy_sig = list(filter(lambda x: x == 1, signals)) sell_sig = list(filter(lambda x: x == 2, signals)) print(f"buy_sig= {len(buy_sig)}") print(f"sell_sig= {len(sell_sig)}") if len(buy_sig) > 0 and len(buy_sig) > len(sell_sig): self.buy(testing_number=i) elif len(sell_sig) > 0 and len(sell_sig) > len(buy_sig): self.sell(testing_number=i) self.show_wallet() self.show_wallet() def ask_symbol_and_golden_crosses(self): col1, col2 = st.beta_columns(2) with col1: self.ask_symbol() with col2: self.show_will_be_taken() def find_golden_cross(self, liste=None): if liste is not None: self.coin_list = liste for i in self.coin_list: ohlc = self.candles(trade_symbol=i) df = self.candles_to_df(ohlc) tarih, acilis, close, high, low = self.get_candle_data(df=df) self.get_triple_ma(close=close) result = self.signals("tripleMA", print_signal=False) print(result) if result == 1: self.TRADE_SYMBOL = i else: print("Golden Cross Bulunamadı") else: # self.coin_list = self.get_all_coins_list()[-500:] self.coin_list = ["UNIUSDT", "TVKBUSD", "SUPERUSDT"] for index, i in enumerate(self.coin_list): parites = [ "BTC", "ETH", "BNB", "PAX", "SDS", "SDC", "BRL", "AUD", "GBP", "EUR", "TRY" ] if i[-3:] in parites: continue if index % 10 == 0: time.sleep(5) print(i) try: ohlc = self.candles(trade_symbol=i) except Exception: continue df = self.candles_to_df(ohlc) tarih, acilis, close, high, low = self.get_candle_data(df=df) result = self.signals("tripleMA", print_signal=False, closes=close) if result == 1: print(f"Golden Cross Bulundu Symbol: {i}") self.winners.append(i) StreamlitView.is_executed_golden_cross = True print(self.winners) return self.winners def get_all_coins_list(self): info = self.client.get_exchange_info() liste = [i["symbol"] for i in info["symbols"]] return liste def show_golden_crosses(self): if not StreamlitView.is_executed_golden_cross or len(self.winners) < 1: yes_or_no = st.sidebar.button("Go Golden Cross!") if yes_or_no: self.find_golden_cross() if len(self.winners) > 0: add_selectbox = st.selectbox( "Golden Cross Yapan Coinler", ["TVKBUSD", "BTCUSDT", "ALGOUSDT"]) st.write(add_selectbox) if add_selectbox is not None: self.TRADE_SYMBOL = add_selectbox self.get_candle_data() def show_will_be_taken(self): if len(self.will_be_taken) > 0: add_selectbox = st.selectbox("Alım sinyali üretenler", options=self.will_be_taken) self.TRADE_SYMBOL = add_selectbox self.get_candle_data() def run(self): self.view_side_bar() self.ask_symbol_and_golden_crosses() self.show_chart("candlestick") self.show_chart("supertrend") self.show_chart("rsi") self.show_chart("bband") self.show_chart("ema") self.show_chart("tripleMA")
class binanceCore: def __init__(self, *args, **kwargs): a = kwargs.get('apikey', None) b = kwargs.get('apisecret', None) if a != None and b != None: self.api_key = a self.api_secret = b else: self.api_key = '' self.api_secret = '' self.client = Client(self.api_key, self.api_secret) self.client.API_URL = 'https://testnet.binance.vision/api' """ General Data Endpoint """ def get_ping_binance(self): ''' This Api for Check api binance ''' print("apikey -> {}, apisecret -> {}".format(self.api_key, self.api_secret)) return self.client.ping() def get_serverTime_binance(self): print("apikey -> {}, apisecret -> {}".format(self.api_key, self.api_secret)) res = self.client.get_server_time() return res['serverTime'] def get_systemStatus_binance(self): print("apikey -> {}, apisecret -> {}".format(self.api_key, self.api_secret)) return self.client.get_system_status() def get_exchangeinfo_binance(self): return self.client.get_exchange_info() def get_symbol_info(self, symbol): print("apikey -> {}, apisecret -> {}".format(self.api_key, self.api_secret)) return self.client.get_symbol_info(symbol) def get_products_binance(self): return self.client.get_products() """ Market Data Endpoint """ def get_order_book_binance(self, symbol, limit=None): if limit != None and limit > 100 and limit < 1000: return self.client.get_order_book(symbol=symbol) else: return self.client.get_order_book(symbol=symbol) def get_recent_trades_binance(self, symbol, limit=None): if limit != None and limit < 500 and limit > 0: return self.client.get_recent_trades(symbol=symbol) else: return self.client.get_recent_trades(symbol=symbol) def get_historical_trades_binance(self, symbol, limit=None): if limit != None and limit < 500 and limit > 0: return self.client.get_historical_trades(symbol=symbol, limit=limit) else: return self.client.get_historical_trades(symbol=symbol) def get_aggregate_trades_binance(self, symbol, limit): if limit != None and limit < 500 and limit > 0: return self.client.get_aggregate_trades(symbol=symbol, limit=limit) else: return self.client.get_aggregate_trades(symbol=symbol) def get_klines_binance(self, symbol, interval): return self.client.get_klines(symbol=symbol, interval=interval) def get_historical_klines_binance(self, symbol, interval): return self.client.get_historical_klines(symbol=symbol, interval=interval) def get_avg_price_binance(self, symbol): return self.client.get_avg_price(symbol=symbol) def get_ticker_binance(self, symbol): return self.client.get_ticker(symbol=symbol) def get_all_tickers_binance(self): return self.client.get_all_tickers() def get_orderbook_tickers_binance(self): return self.client.get_orderbook_tickers()
print '历史成交:---' his_trades = client.get_historical_trades(symbol='BTCUSDT', limit=10, fromId=28457) for item in his_trades: print item print '下一页----' his_trades = client.get_historical_trades(symbol='BTCUSDT', limit=10, fromId=28467) for item in his_trades: print item print '聚集成交---- 只能一小时内 2018-06-11 00:00:00~2018-06-11 01:00:00' agg_trades = client.get_aggregate_trades(symbol='BTCUSDT', startTime=1528646400000, endTime=1528650000000) for item in agg_trades: print item print 'k线 1分钟------- 2018-06-11 00:00:00~2018-06-11 01:00:00' k_lines = client.get_klines(symbol='BTCUSDT', interval=KLINE_INTERVAL_1MINUTE, startTime=1528646400000, endTime=1528650000000) for item in k_lines: print item print '历史k线 可以查询更多时间,就是上述方法的一个优化' k_lines = client.get_historical_klines(symbol='BTCUSDT', interval=KLINE_INTERVAL_1MINUTE,
class ApiCalls: """Collection of api related methods.""" def __init__(self, mw, tp): self.mw = mw self.client = Client(mw.cfg_manager.api_key, mw.cfg_manager.api_secret, { "verify": True, "timeout": 10 }) app.client = self.client self.threadpool = tp def initialize(self): # print("setting client: " + str(self.client)) try: val["coins"] = self.availablePairs() val["accHoldings"] = self.getHoldings() val["tickers"] = self.getTickers() val["apiCalls"] += 3 # userMsg = dict() # accHoldings = dict() self.set_pair_values() self.mw.is_connected = True except (BinanceAPIException, NameError) as e: print("API ERROR") print(str(e)) if "code=-1003" in str(e): print("ja ein api error :)") elif "code=-2014": print("API KEY INVALID") # def get_tether(client): # tether_info = client.get_ticker(symbol="BTCUSDT") # return tether_info def set_pair_values(self): """Set various values based on the chosen pair.""" pair = self.mw.cfg_manager.pair val["decimals"] = len(str(val["coins"][pair]["tickSize"])) - 2 if int(val["coins"][pair]["minTrade"]) == 1: val["assetDecimals"] = 0 else: val["assetDecimals"] = len(str(val["coins"][pair]["minTrade"])) - 2 def availablePairs(self): """ Create a dictonary containing all BTC tradepairs excluding USDT. Keys are: {'symbol': 'ETHBTC', 'tradedMoney': 3024.89552855, 'baseAssetUnit': 'Ξ', 'active': True, 'minTrade': '0.00100000', 'baseAsset': 'ETH', 'activeSell': 66254.102, 'withdrawFee': '0', 'tickSize': '0.000001', 'prevClose': 0.044214, 'activeBuy': 0, 'volume': '66254.102000', 'high': '0.047998', 'lastAggTradeId': 2809764, 'decimalPlaces': 8, 'low': '0.043997', 'quoteAssetUnit': '฿', 'matchingUnitType': 'STANDARD', 'close': '0.047656', 'quoteAsset': 'BTC', 'open': '0.044214', 'status': 'TRADING', 'minQty': '1E-8'} """ # create a local dictionary coins = dict() # API Call products = self.client.get_products() # For every entry in API answer: for i, pair in enumerate(products["data"]): # Check if pair contains BTC, does not contain USDT and if volume is >0 if "BTC" in pair["symbol"] and "USDT" not in pair[ "symbol"] and float(products["data"][i]["volume"]) > 0.0: # Create a temporary dictionary to store keys and values tempdict = dict() # Add every key-value pair to the temp dictionary for key, value in pair.items(): tempdict[key] = value # Add every temp dictionary to the coin dictionary coins[tempdict["symbol"]] = tempdict return coins def getHoldings(self): """Make an inital API call to get BTC and coin holdings.""" # API Call: order = self.client.get_account() accHoldings = dict() for i in range(len(order["balances"])): accHoldings[order["balances"][i]["asset"]] = { "free": order["balances"][i]["free"], "locked": order["balances"][i]["locked"] } return accHoldings def getTickers(self): """Make an initial API call to get ticker data.""" ticker = self.client.get_ticker() # print(str(ticker)) all_tickers = dict() for _, ticker_data in enumerate(ticker): if "BTC" in ticker_data["symbol"]: # print(str(ticker_data)) all_tickers[ticker_data["symbol"]] = ticker_data return all_tickers def getTradehistory(self, pair): """Make an initial API call to get the trade history of a given pair. This is used until updated by websocket data.""" # API call globalList = list() trades = self.client.get_aggregate_trades(symbol=pair, limit=50) for _, trade in enumerate(reversed(trades)): globalList.insert( 0, { "price": str(trade["p"]), "quantity": str(trade["q"]), "maker": bool(trade["m"]), "time": str(trade["T"]) }) return list(reversed(globalList)) def getDepth(self, symbol): """Make an initial API call to get market depth (bids and asks).""" # API Call depth = self.client.get_order_book(symbol=symbol, limit=20) asks = depth["asks"] bids = depth["bids"] return {"bids": bids, "asks": asks} def api_create_order(self, side, pair, price, amount, progress_callback): print("create order: " + str(price) + " " + str(amount)) try: if side == "Buy": order = self.client.order_limit_buy(symbol=pair, quantity=str(amount), price=str(price)) elif side == "Sell": order = self.client.order_limit_sell(symbol=pair, quantity=str(amount), price=str(price)) print("order status: " + str(order)) return order except BinanceAPIException as e: print("create order failed: " + str(e)) print(str(order)) def api_cancel_order(self, client, order_id, symbol, progress_callback): print("cancel order " + str(symbol) + " " + str(order_id)) try: self.client.cancel_order(symbol=symbol, orderId=order_id) except BinanceAPIException as e: print("cancel failed " + str(e)) print(str(self.client)) print(str(symbol)) print(str(order_id)) def api_order_history(self, pair, progress_callback): orders = self.client.get_all_orders(symbol=pair) progress_callback.emit(orders) val["apiCalls"] += 1 def api_history(self, progress_callback): trade_history = self.getTradehistory(self.mw.cfg_manager.pair) progress_callback.emit({"history": reversed(trade_history)}) val["apiCalls"] += 1 def api_depth(self, progress_callback): depth = self.getDepth(self.mw.cfg_manager.pair) val["asks"] = depth["asks"] progress_callback.emit({"asks": val["asks"]}) val["bids"] = depth["bids"] progress_callback.emit({"bids": val["bids"]}) val["apiCalls"] += 1 def api_all_orders(self, progress_callback): print("CLEINT;" + str(self.client)) orders = self.client.get_open_orders() progress_callback.emit(orders) numberPairs = sum(val["pairs"].values()) print("number pairs: " + str(numberPairs)) def api_calls(self): """Inital and coin specific api calls""" worker = Worker(self.api_history) worker.signals.progress.connect(self.mw.live_data.batch_history) self.mw.threadpool.start(worker) worker = Worker(self.api_depth) worker.signals.progress.connect(self.mw.live_data.batch_orderbook) worker.signals.finished.connect(self.mw.limit_pane.t_complete) self.mw.threadpool.start(worker) self.get_trade_history(self.mw.cfg_manager.pair) def get_trade_history(self, pair): worker = Worker(partial(self.api_order_history, pair)) worker.signals.progress.connect(self.mw.history_table.orders_received) self.mw.threadpool.start(worker) def get_kline(self, pair, progress_callback): """Make an API call to get historical data of a coin pair.""" interval = "1m" try: # try since this is used heavily klines = self.client.get_klines(symbol=pair, interval=interval) except (ConnectionError, BinanceAPIException) as e: print(str(e)) progress_callback.emit([klines, pair, interval]) val["apiCalls"] += 1 def cancel_order_byId(self, order_id, symbol): """Cancel an order by id from within a separate thread.""" worker = Worker( partial(self.mw.api_manager.api_cancel_order, app.client, order_id, symbol)) # worker.signals.progress.connect(self.cancel_callback) self.threadpool.start(worker)
class DataEndPoint: """Tools for connecting to exchange""" def __init__(self): self.client = Client(API_KEY, API_SECRET) self.db = Db() def fetch_market_depth(self, symbol='TUSDBTC'): """bid and ask prices for given time and symbol""" depth = self.client.get_order_book(symbol=symbol) df_bid = pd.DataFrame(depth['bids'], columns=['price', 'amount', 'col3']).drop(labels=['col3'], axis=1) df_bid['updatedId'] = depth['lastUpdateId'] df_bid['myUtc'] = dt.datetime.utcnow() df_bid['symbol'] = symbol df_bid['price'] = df_bid['price'].astype(float) df_bid['amount'] = df_bid['amount'].astype(float) self.db.insert_bid_ask(df_bid, 'bid') df_ask = pd.DataFrame(depth['asks'], columns=['price', 'amount', 'col3']).drop(labels=['col3'], axis=1) df_ask['updatedId'] = depth['lastUpdateId'] df_ask['myUtc'] = dt.datetime.utcnow() df_ask['symbol'] = symbol df_ask['price'] = df_ask['price'].astype(float) df_ask['amount'] = df_ask['amount'].astype(float) self.db.insert_bid_ask(df_ask, 'ask') def fetch_all_symbol_prices(self): """prices and all symbols in the given time""" prices = self.client.get_all_tickers() df = pd.DataFrame(prices) self.db.write_df(df=df, index=True, table_name='symbols') def fetch_exchange_info(self): """ Exchange info includes * rateLimits - limits per time intervals - minute, second and day * symbols - large set limiting factors for symbols - tick sizes, min prices, orders, base and quote assets, quote precision, status, full symbol interpretation for a currency pair * current server time * time zone * exchangeFilters - blank field at the moment """ info = self.client.get_exchange_info() # info.keys() # [u'rateLimits', u'timezone', u'exchangeFilters', u'serverTime', u'symbols'] df = pd.DataFrame(info['rateLimits']) self.db.write_df(df=df, index=True, table_name='limits') df = pd.DataFrame(info['symbols']) df1 = df[['baseAsset', 'filters']] self.db.write_df(df=df1, index=True, table_name='symbolFilters') df.drop(labels='filters', inplace=True, axis=1) self.db.write_df(df=df1, index=True, table_name='symbolInfo') # unused fields # info['serverTime'] # info['timezone'] # # UTC # info['exchangeFilters'] self.client.get_all_orders(symbol='TUSDBTC', requests_params={'timeout': 5}) def fetch_general_end_points(self): """ ping - returns nothing for me server time only symbol info - limits for a specific symbol """ self.client.ping() time_res = self.client.get_server_time() status = self.client.get_system_status() # this is the same as exchange info info = self.client.get_symbol_info('TUSDBTC') pd.DataFrame(info) def fetch_recent_trades(self): """ 500 recent trades for the symbol columns: id isBestMatch isBuyerMaker price qty time """ trades = self.client.get_recent_trades(symbol='TUSDBTC') pd.DataFrame(trades) def fetch_historical_trades(self): """ seems the same as recent trades """ trades = self.client.get_historical_trades(symbol='TUSDBTC') pd.DataFrame(trades) def fetch_aggregate_trades(self): """not sure what this does, some trade summary but uses letters as column headers""" trades = self.client.get_aggregate_trades(symbol='TUSDBTC') pd.DataFrame(trades) def fetch_aggregate_trade_iterator(self): agg_trades = self.client.aggregate_trade_iter( symbol='TUSDBTC', start_str='30 minutes ago UTC') # iterate over the trade iterator for trade in agg_trades: print(trade) # do something with the trade data # convert the iterator to a list # note: generators can only be iterated over once so we need to call it again agg_trades = self.client.aggregate_trade_iter( symbol='ETHBTC', start_str='30 minutes ago UTC') agg_trade_list = list(agg_trades) # example using last_id value - don't run this one - can be very slow agg_trades = self.client.aggregate_trade_iter(symbol='ETHBTC', last_id=3263487) agg_trade_list = list(agg_trades) def fetch_candlesticks(self): candles = self.client.get_klines( symbol='BNBBTC', interval=Client.KLINE_INTERVAL_30MINUTE) # this works but I am not sure how to use it for kline in self.client.get_historical_klines_generator( "BNBBTC", Client.KLINE_INTERVAL_1MINUTE, "1 day ago UTC"): print(kline) # do something with the kline def fetch_24hr_ticker(self): """ summary of price movements for all symbols """ tickers = self.get_ticker() pd.DataFrame(tickers).columns # [u'askPrice', u'askQty', u'bidPrice', u'bidQty', u'closeTime', u'count', # u'firstId', u'highPrice', u'lastId', u'lastPrice', u'lastQty', # u'lowPrice', u'openPrice', u'openTime', u'prevClosePrice', # u'priceChange', u'priceChangePercent', u'quoteVolume', u'symbol', # u'volume', u'weightedAvgPrice'] def fetch_orderbook_tickers(client): """ summary of current orderbook for all markets askPrice askQty bidPrice bidQty symbol """ tickers = client.get_orderbook_tickers() pd.DataFrame(tickers)