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("buy order created.\nSymbol:{0:5}\nQuantity:{1:5}".format(symbol,quantity)) 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))
if price['error']: # stop and restart socket bsm.stop() sleep(2) bsm.start() price['error'] = False else: df = price['BTCUSDT'] start_time = df.date.iloc[-1] - pd.Timedelta(minutes=5) df = df.loc[df.date >= start_time] max_price = df.price.max() min_price = df.price.min() if df.price.iloc[-1] < max_price * 0.95: try: order = client.futures_create_order(symbol='ETHUSDT', side='SELL', type='MARKET', quantity=100) break except Exception as e: print(e) elif df.price.iloc[-1] > min_price * 1.05: try: order = client.futures_create_order(symbol='ETHUSDT', side='BUY', type='MARKET', quantity=100) break except Exception as e: print(e) sleep(0.1) # properly stop and terminate WebSocket
class BinanceWrapperAPI(WrapperAPI): # (n) means that parameter is necessary def __init__(self, pair, target, precision): self.pair = pair self.precision = precision self.target = target self.client = Client(keys.binance_api_key, keys.binance_api_secret) def get_my_balance_coin(self, coin): balances = self.client.futures_account_balance() balance = find(lambda v: v['asset'] == coin, balances) return float(balance['withdrawAvailable']) if balance else 0 def get_mycoin(self): return self.get_my_balance_coin('USDT') def get_position_targ(self) -> Tuple[float, bool]: risks = self.client.futures_position_information(symbol=self.target) position = find(lambda v: v['symbol'] == self.pair, risks) amt = float(position['positionAmt']) return abs(amt), amt >= 0 def get_balance_interest(self): amount, _ = self.get_position_targ() return amount def buy_order(self, amount: float): return self.post_order_market("BUY", amount) def sell_order(self, amount: float): return self.post_order_market("SELL", amount) def post_order_market(self, side: str, quantity: float): try: res = self.client.futures_create_order( symbol=self.pair, side=side, type="MARKET", # positionSide=pside, quantity=roundt(quantity, self.precision)) return [True, res['orderId']] except BinanceAPIException as e: raise (e) return [False, e] def get_open_orders(self): return self.client.get_open_orders(symbol=self.pair) def get_position(self) -> Literal["none", "long", "shor"]: amount, posi = self.get_position_targ() if amount == 0: return 'none' return "long" if posi else "shor" def get_ask(self): return float(self.client.get_ticker(symbol=self.pair)['askPrice']) def get_bid(self): return float(self.client.get_ticker(symbol=self.pair)['bidPrice']) def get_order_status(self, id) -> Literal["COMP", "NEW", "EXPIRE"]: try: res = self.client.futures_get_order(symbol=self.pair, orderId=id) if res['status'] == "FILLED": return "COMP" # other: CANCELED, PARTIALLY_FILLED return "NEW" except BinanceAPIException as e: return "EXPIRE"
class MomentumStrategy: def __init__(self): self.client = Client(api_key=API_KEY, api_secret=API_SECRET) self.bsm_s = BinanceSocketManager(self.client) self.bsm_f = BinanceSocketManager(self.client) self.symbol = 'BTCUSDT' self.bet_size = 0.001 self.interval = '15m' self.data_limit = 200 self.lim1 = 0.3 self.lim2 = 0.8 self.last_signal = 0 self.column_names = [ 'open_time', 'open', 'high', 'low', 'close', 'volume', 'close_time', 'quote_asset_volume', 'number_of_trades', 'taker_buy_base_asset_volume', 'taker_buy_quote_asset_volume', 'ignore' ] self.position_open = False self.buy_position = False self.sell_position = False self.client.futures_change_leverage(symbol=self.symbol, leverage=10) self.conn_key_s = self.bsm_s.start_kline_socket( self.symbol, self.web_socket_handler, interval=self.interval) self.bsm_s.start() time.sleep(2) def web_socket_handler(self, data): self.is_kline_closed = data['k']['x'] if self.is_kline_closed: self.calculate_signal() while self.last_signal == self.signal: self.calculate_signal() self.last_signal = self.signal print(self.signal) if not self.position_open: #open order because kline is closed - runs just the first time if self.signal >= self.lim1 and self.signal <= self.lim2: self.position_open = True self.buy_position = True self.buy_bet_size = self.bet_size self.client.futures_create_order(side='BUY', quantity=self.bet_size, symbol=self.symbol, type='MARKET') elif self.signal <= -self.lim1 and self.signal >= -self.lim2: self.position_open = True self.sell_position = True self.sell_bet_size = self.bet_size self.client.futures_create_order(side='SELL', quantity=self.bet_size, symbol=self.symbol, type='MARKET') #close positions if were open because kline is closed else: if self.buy_position: self.position_open = False self.buy_position = False self.client.futures_create_order( side='SELL', quantity=self.buy_bet_size, symbol=self.symbol, type='MARKET') if self.sell_position: self.position_open = False self.sell_position = False self.client.futures_create_order( side='BUY', quantity=self.sell_bet_size, symbol=self.symbol, type='MARKET') #open order because kline is closed if self.signal >= self.lim1 and self.signal <= self.lim2: self.position_open = True self.buy_position = True self.buy_bet_size = self.bet_size self.client.futures_create_order(side='BUY', quantity=self.bet_size, symbol=self.symbol, type='MARKET') elif self.signal <= -self.lim1 and self.signal >= -self.lim2: self.position_open = True self.sell_position = True self.sell_bet_size = self.bet_size self.client.futures_create_order(side='SELL', quantity=self.bet_size, symbol=self.symbol, type='MARKET') def futures_socket(self, data): pass # self.ask = float(data['data']['a']) # self.bid = float(data['data']['b']) # self.price = (self.ask + self.bid)/2 def calculate_signal(self): df = self.client.futures_klines(symbol=self.symbol, interval=self.interval, limit=self.data_limit) df = pd.DataFrame(df, columns=self.column_names) df['close'] = pd.to_numeric(df['close']) nks = [4, 8, 16] nkl = [16, 24, 32] r1 = 12 r2 = 168 l = 198 for i in range(3): df[f'ema_s_{i}'] = EMA(df['close'], window=nks[i]).ema_indicator() df[f'ema_l_{i}'] = EMA(df['close'], window=nkl[i]).ema_indicator() df[f'x{i}'] = df[f'ema_s_{i}'] - df[f'ema_l_{i}'] df[f'y{i}'] = df[f'x{i}'] / np.std(df['close'][l - r1:l]) df[f'z{i}'] = df[f'y{i}'] / np.std(df[f'y{i}'][l - r2:l]) df[f'u{i}'] = (df[f'z{i}'] * np.exp(-(df[f'z{i}']**2) / 4)) / ( np.sqrt(2) * np.exp(-1 / 2)) df['signal'] = (df['u0'] + df['u1'] + df['u2']) / 3 self.signal = df['signal'][l] def strategy(self): pass
class Orders: def __init__(self, SYMBOL, LEWAR, PYRAMID_MAX, ORDER_SIZE, is_it_for_real=False): self.SYMBOL = SYMBOL self.LEWAR = LEWAR self.PYRAMID_MAX = PYRAMID_MAX self.ORDER_SIZE = ORDER_SIZE self.side = {"LONG": 'BUY', "SHORT": 'SELL'} self.side_reversed = { "SHORT": 'BUY', "LONG": 'SELL', "BUY": 'SELL', "SELL": 'BUY' } if is_it_for_real: with open("api_keys.txt") as d: api_keys = d.readlines() api_keys[0] = api_keys[0].strip() self.client = Client(api_keys[0], api_keys[1]) self.zagranie_list = [] try: client.futures_change_margin_type(symbol=self.SYMBOL + 'USDT', marginType="ISOLATED") except: pass self.client.futures_change_leverage(symbol=self.SYMBOL + 'USDT', leverage=self.LEWAR) def update(self): l = len(self.zagranie_list) for i, zagranie in enumerate(self.zagranie_list[::-1]): zagranie.update() if zagranie.state == 'closed': zagranie.close() del zagranie_list[l - 1 - i] def order_size(self, price, balance): #return 0.6**pyramid*ORDER_SIZE*balance*LEWAR/price return self.ORDER_SIZE * balance * self.LEWAR / price def get_balance(self): a = self.client.futures_account_balance() for e in a: if e['asset'] == 'USDT': return float(e['withdrawAvailable']) def positionInfo(self): a = self.client.futures_position_information() for e in a: if e['symbol'] == self.SYMBOL + 'USDT': return e def create_order(self, side, price=None, TARGET_CHANGE=True): print(f"Opening {side}") if len(self.zagranie_list) >= self.PYRAMID_MAX: print("Pyramid max reached") return None balance = self.get_balance() if price: order = self.client.futures_create_order( symbol=self.SYMBOL + 'USDT', side=self.side[side], type='LIMIT', timeInForce=TIME_IN_FORCE_GTC, quantity=self.order_size(price, balance), price=price, newOrderRespType="RESULT") else: order = self.client.futures_create_order( symbol=SYMBOL + 'USDT', side=self.side[side], type='MARKET', quantity=self.order_size( self.price, balance), #JAKIS DOMYSLMY PRICE TRZRBA DAC newOrderRespType="RESULT") if TARGET_CHANGE: if side == "LONG": oco_limit_price = self.price * (1 + TARGET_CHANGE) oco_stop_price = self.price * (1 - TARGET_CHANGE) elif side == "SHORT": oco_limit_price = self.price * (1 - TARGET_CHANGE) oco_stop_price = self.price * (1 + TARGET_CHANGE) zagranie = Zagranie(self, side, order['orderId'], oco_limit_price, oco_stop_price) self.zagranie_list.append(zagranie) return order['orderId'] def close(self, side): print(f"Closing {side}") l = len(self.zagranie_list) for i, zagranie in enumerate(self.zagranie_list[::-1]): if zagranie.side == side: zagranie.close() del zagranie_list[l - 1 - i]
newPosition = -1 * LEVERAGE * allocationUSDT / priceDict[symbol] newPosition = newPosition - (newPosition % minTradeSizes[symbol]) tradeDict[symbol] = newPosition - positionDict[symbol] else: tradeDict[symbol] = -1 * positionDict[symbol] for symbol in symbols: if tradeDict[symbol] == 0: continue elif tradeDict[symbol] > 0: quantity = tradeDict[symbol] client.futures_create_order( symbol=f"{symbol}USDT", side=client.SIDE_BUY, type=client.ORDER_TYPE_LIMIT, timeInForce=client.TIME_IN_FORCE_GTC, price=str(priceDict[symbol]), quantity=f"{quantity:.3}") sleep(0.1) # Comply with API rate limit elif tradeDict[symbol] < 0: quantity = -1 * tradeDict[symbol] client.futures_create_order( symbol=f"{symbol}USDT", side=client.SIDE_SELL, type=client.ORDER_TYPE_LIMIT, timeInForce=client.TIME_IN_FORCE_GTC, price=str(priceDict[symbol]), quantity=f"{quantity:.3}") sleep(0.1) # Comply with API rate limit
def main(): arg = docopt(__doc__, version=version) api_key = getenv('BINANCE_FUTURES_API') sec_key = getenv('BINANCE_FUTURES_SEC') if not api_key and not sec_key: print('please set these environment variables:\n'\ ' BINANCE_FUTURES_API\n'\ ' BINANCE_FUTURES_SEC', file=stderr) return 1 if not api_key: print('environment variable not found: BINANCE_FUTURES_API', file=stderr) return 1 if not sec_key: print('environment variable not found: BINANCE_FUTURES_SEC', file=stderr) return 1 client = Client(api_key, sec_key) sides = { 'buy': Client.SIDE_BUY, 'long': Client.SIDE_BUY, 'sell': Client.SIDE_SELL, 'short': Client.SIDE_SELL, } types = { 'limit': Client.ORDER_TYPE_LIMIT, 'market': Client.ORDER_TYPE_MARKET } tifs = { 'gtc': Client.TIME_IN_FORCE_GTC, 'ioc': Client.TIME_IN_FORCE_IOC, 'fok': Client.TIME_IN_FORCE_FOK } if arg['--verbose']: print(arg, file=stderr) else: sys.tracebacklimit = 0 if arg['--help']: print(__doc__, file=stderr) return 0 elif arg['status']: return client.get_system_status()['status'] elif arg['balance']: if arg['futures']: print(dumps(client.futures_account_balance())) elif arg['spot']: print(dumps(client.get_account()['balances'])) elif arg['coin']: print(dumps(client.futures_coin_account_balance())) return 0 elif arg['show']: if arg['spot']: if arg['orders']: # if arg['--all']: # print(dumps(client.get_all_orders())) # else: print(dumps(client.get_open_orders())) elif arg['order']: symbol = arg['<symbol>'].upper() if arg['futures'] and not symbol.endswith('USDT'): symbol += 'USDT' if arg['cancel']: if arg['futures']: print( client.futures_cancel_order(symbol=symbol, orderid=arg['<orderid>'], timestamp=timemilli())) elif arg['spot']: print('not implemented', file=stderr) else: # create order tif = tifs[arg['--tif']] if arg['<side>'].strip().lower() in sides: side = sides[arg['<side>'].strip().lower()] else: # side is wrong print('error: side should be either "buy|long" or "sell|short"'\ ' not', arg['side'], file=stderr) quantity = float(arg['<quantity>']) if arg['--limit']: if arg['--limit']: price = float(arg['--limit']) type_ = types['limit'] if arg['--test']: print( client.create_test_order(symbol=symbol, side=side, quantity=quantity, price=price, timeInForce=tif, type=type_)) else: # actually send the order if arg['futures']: print( client.futures_create_order( symbol=symbol, side=side, quantity=quantity, price=price, timeInForce=tif, reduceOnly=arg['--reduce-only'], timestamp=timemilli(), type=type_)) elif arg['spot']: print( client.create_order(symbol=symbol, side=side, quantity=quantity, price=price, timeInForce=tif, type=type_)) else: # limit given but price not print('please provide --limit \033[33m<price>\033[0m.') elif arg['--market']: type_ = types['market'] if arg['--test']: print( client.create_test_order(symbol=symbol, side=side, quantity=quantity, type=type_)) else: # actually send the order if arg['futures']: print( client.futures_create_order( symbol=symbol, side=side, quantity=quantity, timestamp=timemilli(), reduceOnly=arg['--reduce-only'], type=type_)) elif arg['spot']: print( client.create_order(symbol=symbol, side=side, quantity=quantity, price=price, type=type_)) else: # limit or market not given print('please provide either '\ '\033[33m --limit <price>\033[0m '\ 'or \033[33m--market\033[0m', file=stderr) else: # no arguments given print(__doc__, file=stderr) return 1
aapl['Close'], aapl['wr_14'], aapl['macd'], aapl['macd_signal']) print("la seƱal vale:", wr_macd_signal) # POSITION close_price = aapl['Close'] if client.futures_position_information( symbol=symbolo)[-1]['positionAmt'] != "0": if client.futures_position_information( symbol=symbolo )[-1]['positionAmt'] != "0" and wr_macd_signal[ -1] == -1 and wr_macd_signal[-2] == 0 and COMPRANDO[0] == 1: close_price = client.futures_create_order(symbol=symbolo, side='SELL', type="MARKET", quantity=cantidad, redueOnly='True') telegram_send.send( messages=["ORDEN DE CERRADA COMPRA WILL+MAC", symbolo]) print("ORDEN DE CERRADA COMPRA WILL+MAC", symbolo) #if len(client.futures_get_open_orders(symbol=symbolo))!=0: #client.futures_cancel_all_open_orders(symbol=symbolo) elif client.futures_position_information( symbol=symbolo)[-1]['positionAmt'] != "0" and wr_macd_signal[ -1] == 1 and wr_macd_signal[-2] == 0 and VENDIENDO[0] == 1: close_price = client.futures_create_order(symbol=symbolo, side='BUY', type="MARKET", quantity=cantidad, redueOnly='True')
dfMarket.loc[dfMarket.index[-1], 'Argent Fixe']= client.futures_account()['maxWithdrawAmount'] dfMarket.loc[dfMarket.index[-1], 'Solde Net'] = client.futures_account()['totalWalletBalance'] try : dfMarket.loc[dfMarket.index[-1], '%PnL'] = (float(client.futures_position_information()[0]['markPrice'])/float(client.futures_position_information()[0]['entryPrice']) -1)* float(client.futures_position_information()[0]['leverage'])*100 except : dfMarket.loc[dfMarket.index[-1], '%PnL'] = 0.0 #check if the last row of SMA_50 is not empty if not (pd.isnull(dfMarket.loc[dfMarket.index[-1], 'SMA_50'])): #STRATEGY dfMarket.loc[dfMarket.index[-1], 'signals'] = np.where((dfMarket.loc[dfMarket.index[-1], 'SMA_3'] > dfMarket.loc[dfMarket.index[-1], 'SMA_10'] and dfMarket.loc[dfMarket.index[-1], 'SMA_3'] > dfMarket.loc[dfMarket.index[-1], 'SMA_50']),1,0) dfMarket.loc[dfMarket.index[-1], 'positions'] = dfMarket.loc[dfMarket.index[-1], 'signals'] - dfMarket.loc[dfMarket.index[-2], 'signals'] print(float(dfMarket.loc[dfMarket.index[-1], 'current_position']) ) print(dfMarket.loc[dfMarket.index[-1], 'positions']) if dfMarket.loc[dfMarket.index[-1], 'positions'] == 1 and float(dfMarket.loc[dfMarket.index[-1], 'current_position']) == 0.0: client.futures_create_order(symbol = symbol, side = 'BUY', type = "MARKET", quantity = float(amount)) print('BUY') elif dfMarket.loc[dfMarket.index[-1], 'positions'] == -1 and float(dfMarket.loc[dfMarket.index[-1], 'positions'])!=0.0: client.futures_create_order(symbol = symbol, side = 'SELL', type = "MARKET", quantity = float(client.futures_position_information()[0]['positionAmt'])) print('SELL') else : print('HOLD') dfMarket.to_csv('tradind_result_30042020.csv', index=False)) #%% RESULT dfMarket = pd.read_csv('tradind_result_30042020.csv', index_col = None) try : dfMarket = dfMarket.drop('Unnamed: 0', 1) except: pass #if dfMarket.loc[dfMarket.index[-1], 'positions']
long = True if MA_short - MA_short_prev < price / short_enter_s and MA_long - MA_long_prev < short_enter_l: short = True if MA_short - MA_short_prev < price / long_exit_s and MA_long - MA_long_prev < long_exit_l: if abs(price / lastbuy + winloss_bias) > winloss_margin: close_long = True if MA_short - MA_short_prev > price / short_exit_s and MA_long - MA_long_prev > -short_exit_l: if abs(lastsell / price + winloss_bias) > winloss_margin: close_short = True if long and holding == 0: holding = 1 lastbuy = price maxbuy = math.floor(holdingUSDT * leverage / price * 1000) / 1000 holdingBTC = maxbuy client.futures_create_order(symbol="BTCUSDT", side="BUY", type="MARKET", quantity=maxbuy) notify.send("Long " + str(maxbuy) + " BTC at " + str(price)) print("Long " + str(maxbuy) + " BTC at " + str(price)) if short and holding == 0: holding = -1 lastsell = price maxsell = math.floor(holdingUSDT * leverage / price * 1000) / 1000 holdingBTC = maxsell client.futures_create_order(symbol="BTCUSDT", side="SELL", type="MARKET", quantity=maxsell) notify.send("Short " + str(maxsell) + " BTC at " + str(price)) print("Short " + str(maxsell) + " BTC at " + str(price)) if close_long and holding == 1:
from candle_monitor import buy_signal, sell_signal from functions import * from api_data import api, secret from binance.client import Client from datetime import datetime as dt import time client = Client(api, secret) tiker = 'ONEUSDT' quantity = 5 try: long_close_order = client.futures_create_order( symbol=tiker, side='SELL', positionSide='BOTH', type='MARKET', quantity=quantity, reduceOnly='true', recvWindow=5000, ) print('done') except: pass
class Buy_sell: def __init__(self): # Enter your own API-key here binance_api_key = '' # Enter your own API-secret here binance_api_secret = '' self.binance_client = Client(api_key=binance_api_key, api_secret=binance_api_secret) def order_limit_buy(self, symbol, q, p): try: # ast.literal_eval( result = self.binance_client.order_limit_buy(symbol=symbol, quantity=q, price=p) return result except: print("order buy error") return None def order_mkt_buy(self, symbol, q): try: result = self.binance_client.order_market_buy(symbol=symbol, quantity=q) return result except: print("order buy error") return None def order_limit_sell(self, symbol, q, p): try: result = self.binance_client.order_limit_sell(symbol=symbol, quantity=q, price=p) return result except: print("order buy error") return None def order_mkt_sell(self, symbol, q): try: result = self.binance_client.order_market_sell(symbol=symbol, quantity=q) return result except: print("order buy error") return None def get_future_account(self): return self.binance_client.futures_account() # positionSide LONG or SHORT # side BUY or SELL def trailing_stop_mkt_future(self, pair, price=None, q=None, side=None, positionSide="BOTH", callbackRate=1, leverage=20): try: self.change_leverage_future(pair, leverage) except: print('No need to change leverage type.') try: self.change_margin_type_future(pair, "ISOLATED") except: print("not need to change margin type") if price: his = self.binance_client.futures_create_order( symbol=pair, side=side, type="TRAILING_STOP_MARKET", quantity=q, activationPrice=price, callbackRate=callbackRate, positionSide=positionSide) else: his = self.binance_client.futures_create_order( symbol=pair, side=side, type="TRAILING_STOP_MARKET", quantity=q, callbackRate=callbackRate, positionSide=positionSide) return his # LONG OR SHORT def mkt_buy_sell_future(self, pair, quantity, positionSide="LONG", side='BUY', leverage=0): his = self.binance_client.futures_create_order( symbol=pair, side=side, type="MARKET", quantity=str(quantity), positionSide=positionSide) return his def limit_buy_sell_future(self, pair, price, quantity, positionSide="LONG", side='BUY', leverage=0): try: self.change_leverage_future(pair, leverage) except: print('No need to change leverage type.') try: self.change_margin_type_future(pair, "ISOLATED") except: print("not need to change margin type") his = self.binance_client.futures_create_order( symbol=pair, side=side, price=str(price), type="LIMIT", quantity=str(quantity), positionSide=positionSide) return his def change_leverage_future(self, pair, leverage): self.change_margin_type_future(pair, "ISOLATED") his = self.binance_client.futures_change_leverage(symbol=pair, leverage=leverage) return his def change_margin_type_future(self, pair, marginType="ISOLATED"): return self.binance_client.futures_change_margin_type( symbol=pair, marginType=marginType)
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