├── BINANCE ├── bot_1 ├── bot_2.py └── bot_3.py ├── KUCOIN ├── bot_1301[kucoin].py └── readme └── LICENSE /BINANCE/bot_1: -------------------------------------------------------------------------------- 1 | # A very simple bot that buys and sells based on reference price changes. 2 | # The reference is set by 'winRate' 3 | 4 | from binance.client import Client 5 | from binance.enums import * 6 | import time 7 | 8 | api_key = '' 9 | api_secret = '' 10 | 11 | tradePair = 'BTCBUSD' 12 | client = Client(api_key, api_secret) 13 | 14 | # Initial values 15 | lastrade = 'BTC' 16 | lasprice = 45351.94 17 | winRate = 1.035 18 | 19 | while True: 20 | # Price & Server Time 21 | price = client.get_ticker(symbol='BTCBUSD') 22 | coitime = client.get_server_time() 23 | coitime = time.strftime('%m/%d/%Y %H:%M:%S', 24 | time.gmtime(coitime['serverTime']/1000.)) 25 | 26 | # SELL BTC (since last trade is BTC) 27 | if lastrade == 'BTC': 28 | balance = client.get_asset_balance(asset='BTC') 29 | coiNumber = format(float(balance['free']),'.4f') 30 | coiprice = format(float(price['askPrice']), '.2f') 31 | if float(coiprice) > lasprice * winRate: 32 | stat = 'sell' 33 | 34 | order = client.order_limit_sell( 35 | symbol='BTCBUSD', 36 | quantity= float(coiNumber), 37 | price= coiprice) 38 | 39 | lastrade = 'BUSD' 40 | lasprice = coiprice 41 | time.sleep(30) # Wait 0.5 minutes to do the trade 42 | else: 43 | stat = 'hold BTC' 44 | 45 | # BUY BTC (since last trade is BUSD) 46 | elif lastrade == 'BUSD': 47 | balance = client.get_asset_balance(asset='BUSD') 48 | coiNumber = format(float(balance['free']),'.4f') 49 | coiprice = format(float(price['askPrice']), '.2f') 50 | test = float(coiNumber)/float(coiprice) 51 | if float(coiprice) * winRate < lasprice: 52 | stat = 'buy' 53 | 54 | order = client.order_limit_buy( 55 | symbol='BTCBUSD', 56 | quantity=format(test, '.4f'), 57 | price= coiprice) 58 | 59 | lastrade = 'BTC' 60 | lasprice = coiprice 61 | time.sleep(30) # Wait 0.5 minutes to do the trade 62 | else: 63 | stat = 'hold BUSD' 64 | 65 | # Print the values 66 | print(coitime + ' ' + balance['free'] + ' ' + price['askPrice'] + ' ' + stat) 67 | time.sleep(60) # Repeat the code every minute 68 | -------------------------------------------------------------------------------- /BINANCE/bot_2.py: -------------------------------------------------------------------------------- 1 | ## Binance Python Bot :] 2 | # This bot calculates the RSI indicator and buys/sells if 3 | # RSI is in range and the price is higher than buy price 4 | 5 | import time 6 | # pip install python-binance 7 | from binance.client import Client 8 | from binance.enums import * 9 | # pip install pandas 10 | import pandas as pd 11 | # pip install numpy 12 | import numpy as np 13 | 14 | 15 | # Functions 16 | def computeRSI (data, time_window): 17 | diff = np.diff(data) 18 | up_chg = 0 * diff 19 | down_chg = 0 * diff 20 | 21 | # up change is equal to the positive difference, otherwise equal to zero 22 | up_chg[diff > 0] = diff[ diff>0 ] 23 | 24 | # down change is equal to negative deifference, otherwise equal to zero 25 | down_chg[diff < 0] = diff[ diff < 0 ] 26 | 27 | up_chg = pd.DataFrame(up_chg) 28 | down_chg = pd.DataFrame(down_chg) 29 | 30 | up_chg_avg = up_chg.ewm(com=time_window-1 , min_periods=time_window).mean() 31 | down_chg_avg = down_chg.ewm(com=time_window-1 , min_periods=time_window).mean() 32 | 33 | rs = abs(up_chg_avg/down_chg_avg) 34 | rsi = 100 - 100/(1+rs) 35 | rsi = int(rsi[0].iloc[-1]) 36 | return rsi 37 | 38 | ################################################## 39 | 40 | # Authenticate to Binance 41 | api_key = '' 42 | api_secret = '' 43 | 44 | ################################################## 45 | 46 | trdPair1 = 'BNB' 47 | trdPair2 = 'BUSD' 48 | winRate = 1.017 49 | client = Client(api_key, api_secret) 50 | 51 | # Console header 52 | print('___DATE______TIME_____BALANCE___RSI____PRICE____STRATEGY___TARGET-PRICE__') 53 | 54 | ################################################## 55 | 56 | # Main loop 57 | while True: 58 | try: 59 | # Initial values 60 | tradePair = trdPair1 + trdPair2 61 | price = client.get_ticker(symbol=tradePair) 62 | btcCount = client.get_asset_balance(asset = trdPair1) 63 | btcCount = float(btcCount['free'])*float(price['askPrice']) 64 | busdCount = client.get_asset_balance(asset = trdPair2) 65 | busdCount = float(busdCount['free']) 66 | 67 | # Find last trade 68 | if btcCount > busdCount: 69 | lastrade = trdPair1 70 | elif btcCount < busdCount: 71 | lastrade = trdPair2 72 | 73 | # Find last price 74 | trades = client.get_my_trades(symbol=tradePair) 75 | trades = trades[len(trades)-1] 76 | lasprice = float(trades['price']) 77 | 78 | klines = client.get_klines(symbol=tradePair, interval='5m', limit='500') 79 | klines2 = client.get_historical_klines(tradePair, Client.KLINE_INTERVAL_1MINUTE, "1 day ago UTC") 80 | close = [float(entry[4]) for entry in klines] 81 | close_array = np.asarray(close) 82 | close_finished = close_array[:-1] 83 | rsi = computeRSI (close_finished, 14) 84 | 85 | # Price & Server Time 86 | price = client.get_ticker(symbol=tradePair) 87 | coitime = client.get_server_time() 88 | coitime = time.strftime('%m/%d/%Y %H:%M:%S', 89 | time.gmtime(coitime['serverTime']/1000.)) 90 | 91 | # SELL 92 | if lastrade == trdPair1: 93 | balance = client.get_asset_balance(asset = trdPair1) 94 | coiNumber = format(float(balance['free'])- 0.0005,'.4f') 95 | coiprice = format(float(price['askPrice']), '.2f') 96 | if float(coiprice) > float(lasprice) * winRate or (rsi > 70): 97 | stat = 'sell' 98 | ## order the sell comand 99 | order = client.order_limit_sell( 100 | symbol=tradePair, 101 | quantity= float(coiNumber), 102 | price= coiprice) 103 | 104 | lastrade = trdPair2 105 | lasprice = coiprice 106 | else: 107 | stat = 'hold' + trdPair1 + ' ' + str(lasprice*winRate) 108 | 109 | # BUY 110 | elif lastrade == trdPair2: 111 | balance = client.get_asset_balance(asset = trdPair2) 112 | coiNumber = format(float(balance['free'])-0.0005,'.4f') 113 | coiprice = format(float(price['askPrice']), '.2f') 114 | test = float(coiNumber)/float(coiprice) 115 | if float(coiprice) * winRate < float(lasprice) or (rsi < 25): 116 | stat = 'buy' 117 | 118 | order = client.order_limit_buy( 119 | symbol=tradePair, 120 | quantity=format(test, '.4f'), 121 | price= coiprice) 122 | 123 | lastrade = trdPair1 124 | lasprice = coiprice 125 | else: 126 | stat = 'hold' + trdPair2 + ' ' + str(lasprice/winRate) 127 | 128 | # Print the values 129 | print(coitime + ' ' + balance['free'] + ' ' + str(rsi) + ' ' + 130 | price['askPrice'] + ' ' + stat) 131 | except: 132 | print(coitime + ' ' + 'an error occured & retrying now') 133 | # Repeat the code every 1.5 minute 134 | time.sleep(60) 135 | 136 | 137 | 138 | 139 | -------------------------------------------------------------------------------- /BINANCE/bot_3.py: -------------------------------------------------------------------------------- 1 | ## Binance Python Bot :] 2 | # This bot calculates RSI and MACD to create buy/sell orders 3 | # This bot also has a stoploss function to act in critical price drops 4 | 5 | import time 6 | import datetime as DT 7 | # pip install python-binance 8 | from binance.client import Client 9 | from binance.enums import * 10 | # pip install pandas 11 | import pandas as pd 12 | # pip install numpy 13 | import numpy as np 14 | 15 | 16 | # pip install python-telegram-bot 17 | ##import logging 18 | ##import telegram 19 | ##from telegram.ext import Updater, CommandHandler, MessageHandler, Filters 20 | ##logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',level=logging.INFO) 21 | ##logger = logging.getLogger(__name__) 22 | ##token = "" 23 | ##updater = Updater(token, use_context=True) 24 | 25 | 26 | # Functions 27 | ################################################## 28 | 29 | def computeRSI (data, time_window): 30 | diff = np.diff(data) 31 | up_chg = 0 * diff 32 | down_chg = 0 * diff 33 | 34 | # up change is equal to the positive difference, otherwise equal to zero 35 | up_chg[diff > 0] = diff[ diff>0 ] 36 | 37 | # down change is equal to negative deifference, otherwise equal to zero 38 | down_chg[diff < 0] = diff[ diff < 0 ] 39 | 40 | up_chg = pd.DataFrame(up_chg) 41 | down_chg = pd.DataFrame(down_chg) 42 | 43 | up_chg_avg = up_chg.ewm(com=time_window-1 , min_periods=time_window).mean() 44 | down_chg_avg = down_chg.ewm(com=time_window-1 , min_periods=time_window).mean() 45 | 46 | rs = abs(up_chg_avg/down_chg_avg) 47 | rsi = 100 - 100/(1+rs) 48 | rsi = int(rsi[0].iloc[-1]) 49 | return rsi 50 | 51 | ################################################## 52 | 53 | def MACD(): 54 | klines2 = client.get_klines(symbol=tradePair, interval='5m', limit='60') 55 | closeVal = [float(entry[4]) for entry in klines2] 56 | closeVal = pd.DataFrame(closeVal) 57 | ema12 = closeVal.ewm(span=12).mean() 58 | ema26 = closeVal.ewm(span=26).mean() 59 | macd = ema26 - ema12 60 | signal = macd.ewm(span=9).mean() 61 | 62 | macd = macd.values.tolist() 63 | signal = signal.values.tolist() 64 | 65 | if macd[-1] > signal[-1] and macd[-2] < signal[-2]: 66 | macdIndicator = 'BUY' 67 | elif macd[-1] < signal[-1] and macd[-2] > signal[-2]: 68 | macdIndicator = 'SELL' 69 | else: 70 | macdIndicator = 'HOLD' 71 | 72 | return macdIndicator 73 | 74 | ################################################## 75 | 76 | def stopLoss(): 77 | today = DT.date.today() 78 | week_ago = today - DT.timedelta(days=6) 79 | week_ago = week_ago.strftime('%d %b, %Y') 80 | klines2 = client.get_historical_klines(tradePair, Client.KLINE_INTERVAL_1DAY, str(week_ago)) 81 | highVal = [float(entry[2]) for entry in klines2] 82 | lowVal = [float(entry[3]) for entry in klines2] 83 | closeVal = [float(entry[4]) for entry in klines2] 84 | avgDownDrop = (sum(highVal)/len(highVal)-sum(lowVal)/len(lowVal))/(sum(closeVal)/len(closeVal)) 85 | stopVal = closeVal[-2]*(1-avgDownDrop) 86 | return stopVal 87 | 88 | ################################################## 89 | 90 | # Authenticate to Binance 91 | api_key = '' 92 | api_secret = '' 93 | 94 | ################################################## 95 | 96 | trdPair1 = 'BNB' 97 | trdPair2 = 'USDT' 98 | winRate = 1.02 99 | client = Client(api_key, api_secret) 100 | 101 | # Console header 102 | print('___DATE______TIME_____BALANCE___RSI__MACD___PRICE______STRATEGY___TARGET-PRICE__') 103 | 104 | ################################################## 105 | 106 | # Main loop 107 | while True: 108 | try: 109 | # Initial values 110 | tradePair = trdPair1 + trdPair2 111 | price = client.get_ticker(symbol=tradePair) 112 | sigNum = len(str(int(float(price['askPrice'])))) 113 | sigNumOfCoin = '.' + str(len(str(int(float(price['askPrice']))))) + 'f' 114 | btcCount = client.get_asset_balance(asset = trdPair1) 115 | btcCount = float(btcCount['free'])*float(price['askPrice']) 116 | busdCount = client.get_asset_balance(asset = trdPair2) 117 | busdCount = float(busdCount['free']) 118 | 119 | # Find last trade 120 | if btcCount > busdCount: 121 | lastrade = trdPair1 122 | elif btcCount < busdCount: 123 | lastrade = trdPair2 124 | 125 | # Find last price 126 | trades = client.get_my_trades(symbol=tradePair) 127 | trades = trades[len(trades)-1] 128 | lasprice = float(trades['price']) 129 | 130 | klines = client.get_klines(symbol=tradePair, interval='5m', limit='500') 131 | klines2 = client.get_historical_klines(tradePair, Client.KLINE_INTERVAL_1DAY, "1 day ago UTC") 132 | close = [float(entry[4]) for entry in klines] 133 | close_array = np.asarray(close) 134 | close_finished = close_array[:-1] 135 | 136 | # Indicators 137 | rsi = computeRSI (close_finished, 14) 138 | 139 | # Price & Server Time 140 | coitime = client.get_server_time() 141 | coitime = time.strftime('%m/%d/%Y %H:%M:%S', 142 | time.gmtime(coitime['serverTime']/1000.)) 143 | 144 | 145 | # SELL 146 | if lastrade == trdPair1: 147 | balance = client.get_asset_balance(asset = trdPair1) 148 | coiNumber = format(float(balance['free']) - 5*10**-sigNum, sigNumOfCoin) 149 | coiprice = format(float(price['askPrice']), '.4f') 150 | if (float(coiprice) > float(lasprice) * winRate) and (rsi > 70 or MACD() == 'SELL'): 151 | stat = 'sell' 152 | ## order the sell comand 153 | order = client.order_limit_sell( 154 | symbol=tradePair, 155 | quantity= float(coiNumber), 156 | price= coiprice) 157 | 158 | lastrade = trdPair2 159 | lasprice = coiprice 160 | prntInfo = coitime + ' ' + 'SELL:' + ' ' + coiprice + ' ' + 'Balance:' + ' ' + balance['free'] 161 | ## updater.dispatcher.bot.send_message(chat_id=1862455948, text=prntInfo) 162 | elif float(coiprice) < stopLoss(): 163 | stat = 'STOPLOSS' 164 | order = client.order_limit_sell( 165 | symbol=tradePair, 166 | quantity= float(coiNumber), 167 | price= coiprice) 168 | 169 | lastrade = trdPair2 170 | lasprice = coiprice 171 | prntInfo = coitime + ' ' + 'StopLoss :((( :' + ' ' + coiprice + ' ' + 'Balance:' + ' ' + balance['free'] 172 | ## updater.dispatcher.bot.send_message(chat_id=1862455948, text=prntInfo) 173 | else: 174 | stat = 'hold' + trdPair1 + ' ' + str(lasprice*winRate) 175 | 176 | 177 | # BUY 178 | elif lastrade == trdPair2: 179 | balance = client.get_asset_balance(asset = trdPair2) 180 | coiNumber = float(balance['free']) 181 | coiprice = format(float(price['askPrice']), '.4f') 182 | test = format(float(coiNumber)/float(coiprice) - 5*10**-sigNum, sigNumOfCoin) 183 | if (float(coiprice) * winRate < float(lasprice)) and (MACD() == 'BUY' or rsi < 30): 184 | stat = 'buy' 185 | 186 | order = client.order_limit_buy( 187 | symbol=tradePair, 188 | quantity=test, 189 | price= coiprice) 190 | 191 | lastrade = trdPair1 192 | lasprice = coiprice 193 | prntInfo = coitime + ' ' + 'BUY:' + ' ' + coiprice + ' ' + 'Balance:' + ' ' + balance['free'] 194 | ## updater.dispatcher.bot.send_message(chat_id=1862455948, text=prntInfo) 195 | else: 196 | stat = 'hold' + trdPair2 + ' ' + str(lasprice/winRate) 197 | 198 | # Print the values 199 | print(coitime + ' ' + balance['free'] + ' ' + str(rsi) + ' ' + MACD() 200 | + ' ' + price['askPrice'] + ' ' + stat) 201 | except: 202 | print(coitime + ' ' + 'an error occured & retrying now') 203 | # Repeat the code every 1 minute 204 | time.sleep(60) 205 | 206 | 207 | 208 | 209 | -------------------------------------------------------------------------------- /KUCOIN/bot_1301[kucoin].py: -------------------------------------------------------------------------------- 1 | # kucoin(pip install kucoin-python) -- bolt1304 2 | 3 | api_key = '' 4 | api_secret = '' 5 | api_passphrase = '' 6 | eth_acc = '' 7 | kcs_acc = '' 8 | btc3l_acc = '' 9 | 10 | asset = 'BTC' 11 | fiat = 'USDT' 12 | 13 | import time 14 | import numpy as np 15 | import pandas as pd 16 | import datetime as DT 17 | 18 | print('----TIME-------------PRICE--RSI---STRATEGY') 19 | 20 | while True: 21 | try: 22 | from kucoin.client import Market 23 | client = Market(api_key, api_secret, api_passphrase, 24 | url='https://api.kucoin.com') 25 | price = client.get_ticker(asset+'-'+fiat) 26 | price = price['price'] 27 | orders = client.get_aggregated_orderv3(asset+'-'+fiat) 28 | klines = client.get_kline(asset+'-'+fiat, '1min') 29 | server_time = time.strftime('%m/%d/%Y %H:%M:%S', 30 | time.gmtime(client.get_server_timestamp()/1000.)) 31 | 32 | 33 | from kucoin.client import User 34 | client = User(api_key, api_secret, api_passphrase) 35 | fiat_balance = client.get_account('612a5bd4fdacf4000769936e') 36 | fiat_balance = fiat_balance['available'] 37 | coin_balance = client.get_account(kcs_acc) 38 | coin_balance = coin_balance['available'] 39 | 40 | 41 | from kucoin.client import Trade 42 | client = Trade(api_key, api_secret, api_passphrase, is_sandbox=False) 43 | last_price = pd.DataFrame(client.get_order_list()) 44 | last_price = last_price.loc[0]['items']['price'] 45 | 46 | 47 | orderBids = np.array(list(orders.values()), dtype=object)[2] 48 | orderAsks = np.array(list(orders.values()), dtype=object)[3] 49 | orderBidAmount = pd.DataFrame([float(entry[1]) for entry in orderBids]) 50 | orderAskAmount = pd.DataFrame([float(entry[1]) for entry in orderAsks]) 51 | 52 | buyOrders = float(orderBidAmount.iloc[0:500].sum()) 53 | sellOrders = float(orderAskAmount.iloc[0:500].sum()) 54 | orderRate = int(buyOrders/(buyOrders + sellOrders)*100) 55 | 56 | 57 | if float(price) > float(last_price) and orderRate < 40: 58 | signal = 'SELL' 59 | elif orderRate > 85: 60 | signal = 'BUY' 61 | elif float(price) < float(last_price)*0.75: 62 | signal = 'limit_loss' 63 | else: 64 | signal = 'wait' 65 | 66 | 67 | if signal == 'BUY': 68 | if float(fiat_balance) > float(coin_balance)*float(price): 69 | from kucoin.client import Trade 70 | client = Trade(api_key, api_secret, api_passphrase, is_sandbox=False) 71 | client.create_limit_order(asset+'-'+fiat, 'buy', 72 | format(int((float(fiat_balance)/float(price))-0.005),'.2f'), 73 | price) 74 | signal = 'BUY ordered @ ' + price 75 | elif signal == 'SELL': 76 | if float(coin_balance)*float(price) > float(fiat_balance): 77 | from kucoin.client import Trade 78 | client = Trade(api_key, api_secret, api_passphrase, is_sandbox=False) 79 | client.create_limit_order(asset+'-'+fiat, 'sell', 80 | format(float(coin_balance)-0.005,'.3f'), price) 81 | signal = 'SELL ordered @ ' + price 82 | elif signal == 'limit_loss': 83 | if float(coin_balance)*float(price) > float(fiat_balance): 84 | from kucoin.client import Trade 85 | client = Trade(api_key, api_secret, api_passphrase, is_sandbox=False) 86 | client.create_market_order(asset+'-'+fiat, 'sell', size=coin_balance) 87 | 88 | except: 89 | signal = signal 90 | 91 | 92 | print(server_time + ' ' + price + ' ' + str(orderRate) + ' ' + signal) 93 | time.sleep(60) 94 | -------------------------------------------------------------------------------- /KUCOIN/readme: -------------------------------------------------------------------------------- 1 | Due to the changes in BINANCE API regulations, I will create a side project with ku-coin. 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 OddPudding 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | --------------------------------------------------------------------------------