def volume_analysis(client, market, TIME_FRAME_STEP, TIME_FRAME_DURATION): NUM_PRICE_STEP = 20 candles = utilities.get_candles(client, market, TIME_FRAME_STEP, TIME_FRAME_DURATION) priceMin = candles['close'].min() priceMax = candles['close'].max() priceStep = (priceMax - priceMin) / NUM_PRICE_STEP volumeAnalysis = pd.DataFrame(index=np.arange(NUM_PRICE_STEP), columns=[ 'price_min', 'price_max', 'price', 'buy_volume', 'sell_volume' ]) volumeAnalysis['price_min'] = \ [priceMin+(i-1)*priceStep for i in np.arange(1, NUM_PRICE_STEP+1)] volumeAnalysis['price_max'] = \ [priceMin+i*priceStep for i in np.arange(1, NUM_PRICE_STEP+1)] volumeAnalysis['price'] = \ .5*(volumeAnalysis['price_min']+volumeAnalysis['price_max']) volumeAnalysis['buy_volume'] = \ [sum(candles\ [volumeAnalysis['price_min'][i]<=candles['close']]\ [candles['close']<=volumeAnalysis['price_max'][i]]['buyQuoteVolume']) \ for i in np.arange(NUM_PRICE_STEP)] volumeAnalysis['sell_volume'] = \ [sum(candles\ [volumeAnalysis['price_min'][i]<=candles['close']]\ [candles['close']<=volumeAnalysis['price_max'][i]]['sellQuoteVolume']) \ for i in np.arange(NUM_PRICE_STEP)] return volumeAnalysis
def asset_analysis(client, asset): marketList = pd.DataFrame(client.get_products()['data']) marketList = marketList[marketList['baseAsset'] == asset] marketList['volume'] = pd.to_numeric(marketList['volume']) marketList = marketList.sort_values('volume', ascending=False) msg = '' for index in marketList.index: market = marketList.at[index, 'symbol'] candles = utilities.get_candles(client, market, timeFrame='5m', timeDuration='30 minutes ago utc') result = pd.DataFrame(columns=['Duration', ': Buy ', ' Sell ']) for i in [2, 1, 0]: result.loc[2 - i] = [ str(5 * (i + 2**i)) + ' mins', "{0:,.2f}".format( candles['buyQuoteVolume'].iloc[-max(3 * i, 1):].sum()), "{0:,.2f}".format( candles['sellQuoteVolume'].iloc[-max(3 * i, 1):].sum()) ] msg = msg+'#'+market+' '\ "{0:,.2f}".format(float(marketList.at[index, 'volume']))+' ('+\ "{0:,.2f}".format(float(marketList.at[index, 'volume']/sum(marketList['volume'])*100))+'%)'+\ '\nP: '+"{0:,.8f}".format(float(marketList.at[index, 'close']))+\ ' V: '+"{0:,.2f}".format(float(marketList.at[index, 'tradedMoney'])) for i in range(len(result)): msg = msg+'\n'+result[result.columns[0]].loc[i]+\ result.columns[1]+'*'+result[result.columns[1]].loc[i]+'*'+\ result.columns[2]+'*'+result[result.columns[2]].loc[i]+'*' msg = msg + '\n' return msg
def stop_hunt(client, stophuntRatio, TIME_FRAME, TIME_FRAME_DURATION): marketList = utilities.get_market_list(client, 'BTC') marketList['stop_hunt'] = 1. for i in marketList.index: market = marketList.at[i, 'symbol'] candles = utilities.get_candles(client, market, TIME_FRAME, TIME_FRAME_DURATION) candle = candles[candles['low'] < stophuntRatio * candles['close']] if len(candle) >= 1: marketList.at[i, 'stop_hunt'] = (candle['low'] / candle['close']).min() candidateList = marketList[marketList['stop_hunt'] < 1.] candidateList = candidateList.sort_values( 'stop_hunt', ascending=True)['symbol'].tolist() msg = '#STOPHUNT\n' msg = msg + ' '.join([item[:-3] for item in candidateList]) return msg
def altcoin_scan(client): marketList = utilities.get_market_list(client) TIME_FRAME = '4h' TIME_FRAME_DURATION = '30 days ago UTC' for index in marketList.index: market = marketList.at[index, 'symbol'] candles = utilities.get_candles(client, market, TIME_FRAME, TIME_FRAME_DURATION) candles['middle'] = .5 * (candles['open'] + candles['close']) bottomIndex = candles['middle'].idxmin() bottom = candles.at[bottomIndex, 'middle'] bottomCandles = candles[candles['low'] <= bottom] bottomIndices = [] for k, g in groupby(enumerate(bottomCandles.index), lambda x: x[0] - x[1]): group = (map(itemgetter(1), g)) group = list(map(int, group)) bottomIndices.append((group[0], group[-1])) marketList.at[index, 'n_bottom'] = len(bottomIndices) marketList.at[index, 'bottom'] = bottom marketList.at[index, 'price'] = candles.at[candles.index[-1], 'close'] marketList['diff'] = (marketList['price'] - marketList['bottom']) / marketList['bottom'] * 100 marketList = marketList.sort_values('diff', ascending=True) marketList = marketList.sort_values('n_bottom', ascending=False) marketListBTC, marketListUSDT = utilities.market_classify(client) marketListBTC = marketList[marketList['symbol'].isin(marketListBTC)] marketListBTC = marketListBTC.set_index('symbol') for i in marketList.index: try: if marketList['symbol'].at[i][-4:] != 'USDT': marketList = marketList.drop(i) except Exception: pass marketList = marketList.set_index('symbol') try: marketListBTC.to_csv('data/market_list_btc.csv') marketList.to_csv('data/market_list_usdt.csv') except Exception: pass return marketListBTC, marketList
def active_trading(client, MIN_COUNT=10, VOL_LB=30, VOL_UB=1000): marketList = pd.DataFrame(client.get_products()['data']) marketList = marketList[marketList['marketName'] == 'BTC'] marketList = marketList[marketList['tradedMoney'] <= VOL_UB] marketList = marketList[marketList['tradedMoney'] >= VOL_LB] n_trades = [] buy_volume = [] sell_volume = [] for coin in marketList['symbol']: try: candles = utilities.get_candles(client, coin, '1m', '1 hour ago UTC') n_trades.append(sum(candles['n_trades'].iloc[-MIN_COUNT:])) buy_volume.append("{0:,.2f}".format( sum(candles['buyQuoteVolume'].iloc[-MIN_COUNT:]))) sell_volume.append("{0:,.2f}".format( sum(candles['sellQuoteVolume'].iloc[-MIN_COUNT:]))) except Exception: n_trades.append(0) buy_volume.append(0) sell_volume.append(0) marketList['n_trades'] = n_trades marketList['buy_volume'] = buy_volume marketList['sell_volume'] = sell_volume marketList = marketList[(marketList['n_trades'] >= 100)] marketList = marketList.sort_values('n_trades', ascending=False) accumulateAnalysis = pd.DataFrame() accumulateAnalysis['symbol'] = marketList['symbol'] accumulateAnalysis['n_trades'] = marketList['n_trades'] accumulateAnalysis['buy_volume'] = marketList['buy_volume'] accumulateAnalysis['sell_volume'] = marketList['sell_volume'] msg = '#MARKET Last ' + str(MIN_COUNT) + 'min' for i in accumulateAnalysis.index: msg = msg+'\n'+accumulateAnalysis.at[i, 'symbol'][:-3]+\ ' ('+str(accumulateAnalysis.at[i, 'n_trades'])+') '+\ ' Buy *'+accumulateAnalysis.at[i, 'buy_volume']+'* '+\ ' Sell *'+accumulateAnalysis.at[i, 'sell_volume']+'*' if float(accumulateAnalysis.at[i, 'buy_volume']) >= float( accumulateAnalysis.at[i, 'sell_volume']): msg = msg + ' (+)' else: msg = msg + ' (-)' return accumulateAnalysis, msg
def analysis_visual(client, market, TIME_FRAME_STEP, TIME_FRAME, TIME_FRAME_DURATION): f, ax = plt.subplots(2, len(TIME_FRAME), gridspec_kw={'height_ratios': [1, 1]}) f.set_size_inches(20 * len(TIME_FRAME), 20) for i in np.arange(len(TIME_FRAME)): candles = utilities.get_candles(client, market, TIME_FRAME[i], TIME_FRAME_DURATION[i]) volumeAnalysis = volume_analysis(client, market, TIME_FRAME_STEP[i], TIME_FRAME_DURATION[i]) try: ax1 = ax[0, i] ax2 = ax[1, i] except Exception: ax1 = ax[0] ax2 = ax[1] axt = ax1.twiny() axt.barh(volumeAnalysis['price'], volumeAnalysis['buy_volume'], color='gray', edgecolor='w', height=volumeAnalysis['price'][1] - volumeAnalysis['price'][0], align='center', alpha=0.25) axt.barh(volumeAnalysis['price'], volumeAnalysis['buy_volume'] + volumeAnalysis['sell_volume'], color='gray', edgecolor='w', height=volumeAnalysis['price'][1] - volumeAnalysis['price'][0], align='center', alpha=0.25) axt.set_xticks([]) for tic in axt.xaxis.get_major_ticks(): tic.tick1On = tic.tick2On = False tic.label1On = tic.label2On = False visual.candlestick2_ohlc(ax1, candles['open'], candles['high'], candles['low'], candles['close'], width=0.6, alpha=1) ax1.plot(candles['close'].rolling(7).mean(), linewidth=4, color='violet', label='Moving Average (7)') ax1.plot(candles['close'].rolling(13).mean(), linewidth=4, color='orange', label='Moving Average (13)') ax1.yaxis.grid(True) for tic in ax1.xaxis.get_major_ticks(): tic.tick1On = tic.tick2On = False tic.label1On = tic.label2On = False ax1.set_xticks([]) ax1.set_xlim(.5, len(candles)) ax1.set_ylim(candles['low'].min(), candles['high'].max()) ax1.yaxis.set_major_formatter(FormatStrFormatter('%.8f')) ax1.get_yaxis().set_label_coords(-0.075, 0.5) visual.candlestick2_ohlc( ax2, 0 * candles['buyQuoteVolume'], candles['buyQuoteVolume'] + candles['sellQuoteVolume'], 0 * candles['buyQuoteVolume'], candles['buyQuoteVolume'] + candles['sellQuoteVolume'], width=0.6, alpha=.35) visual.candlestick2_ohlc(ax2, 0 * candles['buyQuoteVolume'], candles['buyQuoteVolume'], 0 * candles['buyQuoteVolume'], candles['buyQuoteVolume'], width=0.29, alpha=1, shift=-0.15) visual.candlestick2_ohlc(ax2, candles['sellQuoteVolume'], candles['sellQuoteVolume'], 0 * candles['sellQuoteVolume'], 0 * candles['sellQuoteVolume'], width=0.29, alpha=1, shift=+0.15) ax2.yaxis.grid(True) for tic in ax2.xaxis.get_major_ticks(): tic.tick1On = tic.tick2On = False tic.label1On = tic.label2On = False ax2.set_xticks([]) ax2.set_xlim(.5, len(candles)) ax2.get_yaxis().set_label_coords(-0.075, 0.5) ax2.yaxis.set_major_formatter(FormatStrFormatter('%.2f')) axt = ax2.twinx() candles['OBV'] = candles['buyQuoteVolume'] - candles['sellQuoteVolume'] candles['OBV'] = candles['OBV'].cumsum() axt.plot(candles['OBV'].rolling(7).mean(), linewidth=4, color='violet', label='Simple Moving Average (7)') axt.plot(candles['OBV'].rolling(13).mean(), linewidth=4, color='orange', label='Simple Moving Average (13)') axt.plot(candles['OBV'], linewidth=4, color='indigo', label='Demand and Supply Imbalance') for tic in axt.yaxis.get_major_ticks(): tic.tick1On = tic.tick2On = False tic.label1On = tic.label2On = False ax2.get_xaxis().set_label_coords(0.5, -0.025) ax2.set_xlabel(TIME_FRAME[i].upper(), fontsize=20) if i == 0: ax1.set_ylabel("Volume Profile Visible Range", fontsize=20) ax2.set_ylabel("Buy versus Sell Quote Volume", fontsize=20) plt.legend(loc='upper left', prop={'size': 20}) ax1.set_title(market, fontsize=40, y=1.03, loc='left') f.tight_layout() plt.savefig('img/' + market + '.png', bbox_inches='tight')
def volume_spread_analysis(client, market, NUM_PRICE_STEP, TIME_FRAME_STEP, TIME_FRAME, TIME_FRAME_DURATION): nDigit = abs( int( math.log10( float( client.get_symbol_info(market)['filters'][0] ['tickSize'])))) candles = utilities.get_candles(client, market, TIME_FRAME, TIME_FRAME_DURATION) VRVP = indicator.volume_profile(client, market, NUM_PRICE_STEP, TIME_FRAME_STEP, TIME_FRAME_DURATION) BBANDS = indicator.bbands(candles) VSTOP = indicator.volatility_stop(candles, 20, 2) RSI = indicator.rsi(candles, 14) SMA = indicator.sma(candles) # Visualization VSTOP_COLOR = 'indigo' SMA_COLOR = 'black' BBANDS_COLOR = 'green' VOLUME_COLOR = 'gray' BUY_COLOR = 'black' SELL_COLOR = 'red' VOLATILITY_COLOR = 'black' RSI_COLOR = 'black' f, axes = plt.subplots(4, 1, gridspec_kw={'height_ratios': [3, 1, 1, 1]}) f.set_size_inches(20, 20) ax = axes[0] axt = ax.twiny() axt.barh(VRVP['price'], VRVP['buy_volume'], color='gray', edgecolor='w', height=VRVP['price'][1] - VRVP['price'][0], align='center', alpha=0.25) axt.barh(VRVP['price'], VRVP['buy_volume'] + VRVP['sell_volume'], color='gray', edgecolor='w', height=VRVP['price'][1] - VRVP['price'][0], align='center', alpha=0.25) axt.set_xticks([]) for tic in axt.xaxis.get_major_ticks(): tic.tick1On = tic.tick2On = False tic.label1On = tic.label2On = False visual.candlestick2_ohlc(ax, candles['open'], candles['high'], candles['low'], candles['close'], width=0.6, alpha=1) ax.plot(VSTOP['support'], linewidth=2, color=VSTOP_COLOR, linestyle='-') ax.plot(VSTOP['resistance'], linewidth=2, color=VSTOP_COLOR, linestyle='-') ax.plot(BBANDS['middle_band'], linewidth=1, color=BBANDS_COLOR, linestyle='-') ax.plot(BBANDS['upper_band'], linewidth=1, color=BBANDS_COLOR, linestyle='-') ax.plot(BBANDS['lower_band'], linewidth=1, color=BBANDS_COLOR, linestyle='-') ax.plot(SMA, linewidth=1, color=SMA_COLOR, linestyle='--') if market == 'BTCUSDT': pivotList = [] for i in range(len(VSTOP)): if math.isnan(VSTOP['support'].iat[i]): if not math.isnan(VSTOP['support'].iat[i - 1]): pivotList.append(VSTOP['support'].iat[i - 1]) if math.isnan(VSTOP['resistance'].iat[i]): if not math.isnan(VSTOP['resistance'].iat[i - 1]): pivotList.append(VSTOP['resistance'].iat[i - 1]) pivotList = sorted(pivotList) for pivot in pivotList: ax.text(len(candles) + .5, pivot, str(int(pivot))) ax.yaxis.grid(True) for tic in ax.xaxis.get_major_ticks(): tic.tick1On = tic.tick2On = False tic.label1On = tic.label2On = False ax.set_xticks([]) ax.set_yticks(VRVP['price_min'].append(VRVP['price_max'].tail(1))) ax.set_xlim(-.5, len(candles)) ax.yaxis.set_major_formatter(FormatStrFormatter('%.' + str(nDigit) + 'f')) ax.get_yaxis().set_label_coords(-0.075, 0.5) ax.set_ylabel("Price", fontsize=20) ax.set_title(market + ' ' + TIME_FRAME.upper(), fontsize=30, y=1.03, loc='left') patchList = [ mpatches.Patch(color=VOLUME_COLOR, label='market-profile'), mpatches.Patch(color=VSTOP_COLOR, label='volatility-stop'), mpatches.Patch(color=BBANDS_COLOR, label='bollinger-bands'), mpatches.Patch(color=SMA_COLOR, label='moving-average') ] ax.legend(handles=patchList, loc='best', prop={'size': 20}, ncol=len(patchList), framealpha=0.5) ax = axes[1] visual.candlestick2_ohlc(ax, 0 * candles['assetVolume'], candles['assetVolume'], 0 * candles['assetVolume'], candles['assetVolume'], width=0.6, alpha=.35) visual.candlestick2_ohlc(ax, 0 * candles['buyAssetVolume'], candles['buyAssetVolume'], 0 * candles['buyAssetVolume'], candles['buyAssetVolume'], width=0.28, alpha=1, shift=-0.15) visual.candlestick2_ohlc(ax, candles['sellAssetVolume'], candles['sellAssetVolume'], 0 * candles['sellAssetVolume'], 0 * candles['sellAssetVolume'], width=0.28, alpha=1, shift=+0.15) ax.yaxis.grid(True) for tic in ax.xaxis.get_major_ticks(): tic.tick1On = tic.tick2On = False tic.label1On = tic.label2On = False ax.set_xticks([]) ax.set_xlim(-.5, len(candles)) ax.get_yaxis().set_label_coords(-0.075, 0.5) ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f')) ax.get_xaxis().set_label_coords(0.5, -0.025) ax.set_ylabel("Volume", fontsize=20) patchList = [ mpatches.Patch(color=VOLUME_COLOR, label='volume'), mpatches.Patch(color=BUY_COLOR, label='buy-volume'), mpatches.Patch(color=SELL_COLOR, label='sell-volume') ] ax.legend(handles=patchList, loc='best', prop={'size': 20}, ncol=len(patchList), framealpha=0.5) ax = axes[2] visual.candlestick2_ohlc(ax, 0 * candles['spread'], candles['spread'], 0 * candles['spread'], candles['spread'], width=0.6, colorup=VOLATILITY_COLOR, alpha=.35) ax.yaxis.grid(True) for tic in ax.xaxis.get_major_ticks(): tic.tick1On = tic.tick2On = False tic.label1On = tic.label2On = False ax.set_xticks([]) ax.set_xlim(-.5, len(candles)) ax.get_yaxis().set_label_coords(-0.075, 0.5) ax.yaxis.set_major_formatter(FormatStrFormatter('%.' + str(nDigit) + 'f')) ax.get_xaxis().set_label_coords(0.5, -0.025) ax.set_ylabel("Volatility", fontsize=20) patchList = [ mpatches.Patch(color=VOLATILITY_COLOR, label='average-true-range'), mpatches.Patch(color=BBANDS_COLOR, label='standard-deviation') ] ax.legend(handles=patchList, loc='best', prop={'size': 20}, ncol=len(patchList), framealpha=0.5) axt = ax.twinx() axt.plot(BBANDS['std'], linewidth=2, color=BBANDS_COLOR, linestyle='-') for tic in axt.xaxis.get_major_ticks(): tic.tick1On = tic.tick2On = False tic.label1On = tic.label2On = False axt.set_xticks([]) axt.set_yticks([]) axt.set_xlim(-.5, len(candles)) axt = ax.twinx() axt.plot(VSTOP['ATR'], linewidth=2, color=VOLATILITY_COLOR, linestyle='-') for tic in axt.xaxis.get_major_ticks(): tic.tick1On = tic.tick2On = False tic.label1On = tic.label2On = False axt.set_xticks([]) axt.set_xlim(-.5, len(candles)) ax = axes[3] ax.plot(RSI, linewidth=2, color=RSI_COLOR, linestyle='-') ax.axhline(y=50, color=RSI_COLOR, linestyle='--') ax.axhspan(ymin=20, ymax=80, color=RSI_COLOR, alpha=0.1) ax.axhspan(ymin=30, ymax=70, color=RSI_COLOR, alpha=0.1) ax.yaxis.grid(True) for tic in ax.xaxis.get_major_ticks(): tic.tick1On = tic.tick2On = False tic.label1On = tic.label2On = False ax.set_xticks([]) ax.set_xlim(-.5, len(candles)) ax.get_yaxis().set_label_coords(-0.075, 0.5) ax.yaxis.set_major_formatter(FormatStrFormatter('%.' + str(nDigit) + 'f')) ax.get_xaxis().set_label_coords(0.5, -0.025) ax.set_ylabel("Momentum", fontsize=20) patchList = [mpatches.Patch(color=RSI_COLOR, label='relative-strength')] ax.legend(handles=patchList, loc='best', prop={'size': 20}, ncol=len(patchList), framealpha=0.5) f.tight_layout() plt.savefig('img/' + market + '_' + TIME_FRAME.upper() + '.png', bbox_inches='tight')
def market_movement(client, timeInterval): btcOnlyMarketList, usdtOnlyMarketList = utilities.market_classify(client) marketList = utilities.get_market_list(client, 'BTC') exchangeVolume = pd.DataFrame() totalVolume = pd.DataFrame() buyVolume = pd.DataFrame() sellVolume = pd.DataFrame() for market in btcOnlyMarketList: try: candles = utilities.get_candles(client, market, timeFrame='1d', timeDuration=str(timeInterval) + ' days ago UTC') totalVolume[market] = candles['quoteVolume'] totalVolume = totalVolume.fillna(0.) buyVolume[market] = candles['buyQuoteVolume'] buyVolume = buyVolume.fillna(0.) sellVolume[market] = candles['sellQuoteVolume'] sellVolume = sellVolume.fillna(0.) except Exception: pass exchangeVolume['volume'] = totalVolume.iloc[:, :].sum(axis=1) exchangeVolume['buy-volume'] = buyVolume.iloc[:, :].sum(axis=1) exchangeVolume['sell-volume'] = sellVolume.iloc[:, :].sum(axis=1) f, axes = plt.subplots(2, 1, gridspec_kw={'height_ratios': [1, 1]}) f.set_size_inches(20, 15) ax = axes[0] candles = utilities.get_candles(client, market='BTCUSDT', timeFrame='1d', timeDuration=str(timeInterval) + ' days ago UTC') visual.candlestick2_ohlc(ax, candles['open'], candles['high'], candles['low'], candles['close'], width=0.6, alpha=1) ax.yaxis.grid(True) for tic in ax.xaxis.get_major_ticks(): tic.tick1On = tic.tick2On = False tic.label1On = tic.label2On = False ax.set_xticks([]) ax.set_xlim(.5, timeInterval) ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f')) ax.get_yaxis().set_label_coords(-0.075, 0.5) ax.set_title('Binance Exchange Daily Movement Statistics over ' + str(timeInterval) + ' day period', fontsize=30, y=1.03, loc='center') ax.set_ylabel("Bitcoin Price", fontsize=20) ax = axes[1] visual.candlestick2_ohlc(ax, 0 * exchangeVolume['volume'], exchangeVolume['volume'], 0 * exchangeVolume['volume'], exchangeVolume['volume'], width=0.6, alpha=.35) visual.candlestick2_ohlc(ax, 0 * exchangeVolume['buy-volume'], exchangeVolume['buy-volume'], 0 * exchangeVolume['buy-volume'], exchangeVolume['buy-volume'], width=0.28, alpha=1, shift=-0.15) visual.candlestick2_ohlc(ax, exchangeVolume['sell-volume'], exchangeVolume['sell-volume'], 0 * exchangeVolume['sell-volume'], 0 * exchangeVolume['sell-volume'], width=0.28, alpha=1, shift=+0.15) ax.plot(exchangeVolume['volume'].rolling(window=20).mean(), linewidth=2, color='gray', linestyle='-') ax.yaxis.grid(True) for tic in ax.xaxis.get_major_ticks(): tic.tick1On = tic.tick2On = False tic.label1On = tic.label2On = False ax.set_xticks([]) ax.set_xlim(.5, timeInterval) ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f')) ax.get_yaxis().set_label_coords(-0.075, 0.5) ax.set_ylabel("Altcoin Total Volume (" + str(len(btcOnlyMarketList)) + "/" + str(len(marketList)) + " pairs)", fontsize=20) patchList = [ mpatches.Patch(color='gray', label='volume'), mpatches.Patch(color='black', label='buy-volume'), mpatches.Patch(color='red', label='sell-volume') ] ax.legend(handles=patchList, loc='best', prop={'size': 20}, ncol=1, framealpha=0.5) f.tight_layout() plt.savefig('img/market.png', bbox_inches='tight')