def handle(self, *args, **options): c = Client(settings.BINANCE_API_KEY, settings.BINANCE_SECRET) assets = c.get_all_tickers() for asset in assets: Coin.objects.get_or_create(symbol=asset['symbol']) ei = c.get_exchange_info() # Get coin order filters. for coin_filter in ei['symbols']: symbol = coin_filter['symbol'] lot_filter = next((item for item in coin_filter['filters'] if item["filterType"] == "LOT_SIZE"), None) coin = Coin.objects.get(symbol=symbol) coin.max_qty = lot_filter['maxQty'] coin.min_qty = lot_filter['minQty'] coin.step_size = lot_filter['stepSize'] step_split = lot_filter['stepSize'].split(".") if step_split[0] == '1': coin.step = 0 else: coin.step = len(step_split[1].split("1")[0]) + 1 coin.save()
class App: def __init__(self, market, coin): self.market = market self.coin = coin self.dataset = [] def authorize_client(self): self.client = Client(user.API_KEY, user.API_SECRET) def append_data(self, price): data = self.dataset data.append(price) if len(data) < 5 else data.pop(0) def get_price(self): return [ Decimal(x['price']) for x in self._fetch_api_data() if x['symbol'] == self.market ] def start(self): self.authorize_client() price = self.get_price() self.append_data(price) def _fetch_api_data(self): self.prices = self.client.get_all_tickers() return self.prices
def run_update(event, context): # Getting S3 Bucket File Location bucket_name = environ.get("BUCKET") s3 = boto3.resource("s3") bucket = s3.Bucket(bucket_name) # API_KEY , API_SECRET API_KEY = environ.get("API_KEY") API_SECRET = environ.get("API_SECRET") # Creating Dummy Data binance_client = Client(api_key=API_KEY, api_secret=API_SECRET) all_tradable = binance_client.get_all_tickers() df = pd.DataFrame(all_tradable) file_name = environ.get('COIN_FILE_NAMES') df.to_csv("/tmp/" + file_name, index=False, compression="gzip") # Upload File to s3 path_to_file = f"/tmp/{file_name}" bucket.upload_file(path_to_file, file_name) response = {"statusCode": 200, "body": "Successfully update valid tickers"} return response
class AutoPilot: def __init__(self, key, secret): self.client = Client(api_key=key, api_secret=secret) def get_all_tickers(self) -> list: try: return self.client.get_all_tickers() except Exception as e: print(e) return None def get_symbol_tikcer(self, symbol: str) -> dict: try: if (symbol): return self.client.get_symbol_ticker(symbol=symbol) else: raise ValueError('designate symbol') except Exception as e: print(e) return None def get_symbol_info(self, symbol: str) -> dict: try: if (symbol): return self.client.get_symbol_info(symbol=symbol) else: raise ValueError('designate symbol') except Exception as e: print(e) return None
class ScrapeBinance(): API, API_SECRET = '', '' def __init__(self): self.link = 'https://www.binance.com/en/trade/RVN_BTC' with open('../metadata/binance_keys.txt') as f: keys = f.read() keys = keys.split(',') ScrapeBinance.API, ScrapeBinance.API_SECRET = keys[0], keys[1] self.client = Client(ScrapeBinance.API, ScrapeBinance.API_SECRET) self.fill_json() def fill_json(self): ticker_list = [ symbol['symbol'] for symbol in self.client.get_all_tickers() ] ticker_list = set( [ticker[:-3] for ticker in ticker_list if ticker[-4:] != 'USDT']) with open('meta/coin.json', 'r') as f: coin_info = json.load(f) coin_list = list(coin_info.keys()) for new in list(ticker_list.difference(set(coin_info))): coin_info[new] = '' print(coin_info) with open('meta/coin.json', 'w') as f: json.dump(coin_info, f)
def main(): api_key = config.get(USER_CFG_SECTION, 'api_key') api_secret_key = config.get(USER_CFG_SECTION, 'api_secret_key') client = Client(api_key, api_secret_key) available_tickers = {} for ticker in client.get_all_tickers(): available_tickers[ticker['symbol']] = None global g_state if not (os.path.isfile(g_state._table_backup_file)): initialize_trade_thresholds(client) if config.get(USER_CFG_SECTION, 'current_coin') == '': logger.info("Purchasing {0} to begin trading".format( g_state.current_coin)) buy_alt(client, g_state.current_coin, BRIDGE) logger.info("Ready to start trading") while True: try: time.sleep(5) scout(client, available_tickers) except Exception as e: logger.info('Error while scouting...\n{}\n'.format(e))
def get_market_data(end_time, delay=1): client = Client(api_key, api_secret) fullbook = pd.DataFrame() ticker_list = [x['symbol'] for x in client.get_all_tickers()] while (_dt_dt_.now() < end_time): for symbol in ticker_list: try: depth = pd.DataFrame(client.get_order_book(symbol=symbol)) book_update = pd.DataFrame({ _dt_dt_.now().strftime("%Y%m%d %H:%M:%S.%f"): { 'symbol': symbol, 'q_bid': float(depth.loc[0, 'bids'][1]), 'p_bid': float(depth.loc[0, 'bids'][0]), 'q_ask': float(depth.loc[0, 'asks'][1]), 'p_ask': float(depth.loc[0, 'asks'][0]), 'q_bid_2': float(depth.loc[1, 'bids'][1]), 'p_bid_2': float(depth.loc[1, 'bids'][0]), 'q_ask_2': float(depth.loc[1, 'asks'][1]), 'p_ask_2': float(depth.loc[1, 'asks'][0]) } }) fullbook = fullbook.append(book_update.T) except: pass time.sleep(delay) save_fullbook_data( fullbook, '/home/yizhang/Research/data/%s' % (_dt_dt_.now().strftime("%Y/%m/%d/")))
def get_balances(self): '''Gets the current balance info using python-binance module. Note that shows in total current USDT value''' # Initiate the class account = Client(api_key=api_key, api_secret=secret_key) # GET account information account_dictionary = account.get_account() total_balance = 0 pair_info_all = account.get_all_tickers() # Remove non-USDT pair info pair_info = [x for x in pair_info_all if "USDT" in x["symbol"][-4:]] for i in range(len(account_dictionary["balances"])): pair_name = account_dictionary['balances'][i]['asset'] pair_name_usdt = f"{pair_name}USDT" if pair_name == "USDT": total_balance += float(account_dictionary['balances'][i]['free']) for j in range(len(pair_info)): if pair_name_usdt == pair_info[j]['symbol']: total_balance += (float(account_dictionary["balances"][i]["free"]) + float( account_dictionary["balances"][i]["locked"])) \ * float(pair_info[j]['price']) return total_balance
def search_for_coin(): try: #initiate client client = Client(api_key, api_secret) #get balance #balance = client.get_asset_balance(asset='BTC') # get all symbol prices prices = client.get_all_tickers() # find coin for coin in prices: if coin['symbol'] == pairing: print('[!] Pairing Found [!]') price = coin['price'] print('[!] Pairing Price: ' + price + 'BTC [!]') created_order = buy_order(client, price) if created_order is True: return True else: print('[!] ERROR! Retrying... [!]') return False except (KeyboardInterrupt, SystemExit): # debug raise
def populate_data(path, base_currency="ETH", interval=Client.KLINE_INTERVAL_1HOUR, start="30 January, 2016", end="1 April, 2019"): """Populate a directory for data within a time range and interval for a base asset. Args: path: The directory in which to store the data. base_currency: The base asset we want the data for. interval: The candle interval, eg. 1 hour, as a binance enum. start: The start date. end: The end date. """ symbols = [] client = Client("", "") tickers = client.get_all_tickers() for ticker in tickers: symbol = ticker['symbol'] if symbol.endswith(base_currency): symbols.append(symbol) for symbol in symbols: klines = get_historical_klines(symbol, interval, start, end) with open("{}/{}_1h.json".format(path, symbol), 'w') as f: f.write(json.dumps(klines))
class Binance(): def __init__(self): self.client = Client("hziRqaoLzBRMlfwULTS66dm527DMVWjF3rQlPJlH5h9kdJwPg4T9MOgeLXYtjhX1", "syLnOpemHBzlyTo2xZEs9vaILt3RNikpdbTHijLFvqaow7HoddxfR3lXgpvRSgVw") self.infos = self.client.get_all_tickers() def get_price(self): final_result = [] for info in self.infos: for symbol in network_symbols: if info["symbol"] == "{}USDT".format(symbol): final_result.append(info) return final_result def pure_price(self): prices = [] for price in self.get_price(): price["symbol"] = price["symbol"][:-4] prices.append(price) return prices def calculate_interest(current_price , last_price): return (current_price - last_price) / last_price * 100 def get_kline(self, network): return binance.client.get_klines(symbol="%sUSDT"%network, interval="1m")
class BinanceListingObtainer(ListingObtainer): _client: Client def __init__(self, propertiesFile="binance_properties.json"): super().__init__() api_key, api_secret = self._getKeysFromFile(propertiesFile) self._client = Client(api_key=api_key, api_secret=api_secret) def obtain(self) -> pd.DataFrame: dictionary = {"Ticker": []} tickers = self._client.get_all_tickers() for ticker in tickers: dictionary["Ticker"].append(ticker["symbol"]) self.listings = pd.DataFrame(dictionary, columns=["Ticker"]) return self.listings def _getKeysFromFile(self, propertiesFile: str): try: with open(propertiesFile, mode='r') as file: data = json.load(file) apiKey = data["API Key"] apiKeySecret = data["API Key Secret"] return apiKey, apiKeySecret except: print( "You are missing " + propertiesFile + ". Please ask Robert" \ "(robert.ciborowski" "@mail.utoronto.ca) for " "help.")
class BinanceHelper(object): def __init__(self, api_key, api_secret, base_currency, coin_currency): self.client = Client(api_key, api_secret) self.base_currency = base_currency self.coin_currency = coin_currency self.symbol = coin_currency + base_currency def float_precision(self, f, n): n = int(math.log10(1 / float(n))) f = math.floor(float(f) * 10**n) / 10**n f = "{:0.0{}f}".format(float(f), n) return str(int(f)) if int(n) == 0 else f def get_price(self): price = None tickers = self.client.get_all_tickers() for ticker in tickers: if ticker['symbol'] == self.symbol: price = float(ticker['price']) return price def get_tick_and_step_size(self): tick_size = None step_size = None symbol_info = self.client.get_symbol_info(self.symbol) for filt in symbol_info['filters']: if filt['filterType'] == 'PRICE_FILTER': tick_size = float(filt['tickSize']) elif filt['filterType'] == 'LOT_SIZE': step_size = float(filt['stepSize']) return tick_size, step_size def get_balance(self, currency): return float(self.client.get_asset_balance(asset=currency)['free']) def get_buy_info(self): tick_size, step_size = self.get_tick_and_step_size() price = float(self.float_precision(self.get_price(), tick_size)) coin_currency_quantity = float( self.float_precision( self.get_balance(self.base_currency) / price, step_size)) return price, coin_currency_quantity def get_sell_info(self): tick_size, step_size = self.get_tick_and_step_size() price = float(self.float_precision(self.get_price(), tick_size)) coin_currency_quantity = float( self.float_precision(self.get_balance(self.coin_currency), step_size)) return price, coin_currency_quantity def buy(self): price, quantity = self.get_buy_info() self.client.order_market_buy(symbol=self.symbol, quantity=quantity) def sell(self): price, quantity = self.get_sell_info() self.client.order_market_sell(symbol=self.symbol, quantity=quantity)
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
def coin_prices(self, watch_list): #Will print to screen, prices of coins on 'watch list' #returns all prices prices = Client.get_all_tickers(self) print("\nSelected (watch list) Ticker Prices: ") for price in prices: if price['symbol'] in watch_list: print(price) return prices
def compute_pnl(): json_payload = request.get_json() binance_api_key = json_payload['API_KEY'] binance_api_secret = json_payload['API_SECRET'] order_history = json_payload['order_history'] binance_client = Client(api_key=binance_api_key, api_secret=binance_api_secret) all_tradable = binance_client.get_all_tickers() global prices prices = {p['symbol']: p['price'] for p in all_tradable} # Step 1: Get quantities of the coins valid_orders = [o for o in order_history if float(o['executedQty']) > 0] coin_obj_dict = {} pnl = {} for order in valid_orders: coin = order['symbol'] if order['type'] == 'REVERSE': order['price'] = get_reverse_trade_price(order, binance_client) if coin not in coin_obj_dict: coin_obj_dict[coin] = CoinProfitLoss(coin) cpl_object = coin_obj_dict[coin] if order['side'] == 'BUY': cpl_object.buy(float(order['executedQty']), float(order['price'])) else: cpl_object.sell(float(order['executedQty']), float(order['price'])) category = [] ureal_pnl = [] real_pnl = [] for coin in coin_obj_dict: if coin_obj_dict[coin].cost_basis < 10: continue unrealised_pnl = coin_obj_dict[coin].get_unrealised_pnl( float(prices[coin])) realised_pnl = coin_obj_dict[coin].get_realised_pnl() category.append({"label": coin}) ureal_pnl.append({"value": str(unrealised_pnl)}) real_pnl.append({"value": str(realised_pnl)}) total_pnl = sum(ureal_pnl) + sum(real_pnl) total_pnl_arr = [ureal_pnl[i] + real_pnl[i] for i in range(len(ureal_pnl))] most_profitable = category[total_pnl_arr.index(max(total_pnl_arr))] least_profitable = category[total_pnl_arr.index(min(total_pnl_arr))] return jsonify({ "code": 200, "data": { "categories": category, "ureal_pnl": ureal_pnl, "real_pnl": real_pnl, "total_pnl": total_pnl, "most_profitable": most_profitable, "least_profitable": least_profitable } }), 200
def main(): api_key = os.environ['BINANCE_API'] api_secret = os.environ['BINANCE_SECRET'] client = Client(api_key, api_secret) all_tickers = client.get_all_tickers() dst_dir = Path('Binance') interval = '5m' # fill in all get_all_kline args except for symbol so we can use in multithreading thread_func = partial(get_all_klines, client=client, interval=interval, dst_dir=dst_dir) total_erw = 0 # count of total estimated request weight symbol_batch = [ ] # list to be filled with symbols for single multithread run through for i, ticker in enumerate(all_tickers): symbol = ticker['symbol'] erw = estimate_request_weight(symbol, interval, dst_dir, client) total_erw += 2 # add 2 for estimate_request_weight function calls just to be safe if total_erw + erw > 1100: # api request limit is 12000 per minute print(i, symbol_batch) start_time = datetime.now() with concurrent.futures.ThreadPoolExecutor() as executor: futures = list(executor.map(thread_func, symbol_batch)) for filepath, data_df in futures: # save data outside of multithreading. suspected errors trying to save w/in multithreading. also easier to line up in console output. data_df.to_csv(filepath) print(f'saved to {filepath}') end_time = datetime.now() duration = start_time - end_time if duration < timedelta( minutes=1): # pause if outpacing api request limit sleep_time = timedelta(minutes=1) - duration time.sleep(sleep_time.seconds) # restart symbol batch and total_erw w/ data from current ticker symbol_batch = [symbol] total_erw = erw elif erw != 0: # skip symbols with 0 erw # 0 erw means less than days worth of data to download (see estimate_request_weight function) # add symbol to symbol_batch, update total_erw counter symbol_batch.append(symbol) total_erw += erw if i % 100 == 0: print(i) # one last symbol_batch left with concurrent.futures.ThreadPoolExecutor() as executor: futures = list(executor.map(thread_func, symbol_batch)) for filepath, data_df in futures: data_df.to_csv(filepath) print(f'saved to {filepath}')
def get_all_tickers(api_key=binance_api_key, api_secret=binance_api_secret): client = Client(api_key=api_key, api_secret=api_secret) all_tickers_data = client.get_all_tickers() tickers = [] for ticker_data in all_tickers_data: tickers.append(ticker_data['symbol']) return np.array(tickers)
def get_binance_info(): client = Client(api_key_binance, api_secret_binance) prices = client.get_all_tickers() for item in prices: if "BTCUSDT" in item["symbol"]: btc_price = item["price"] if "ETHUSDT" in item["symbol"]: eth_price = item["price"] return float(btc_price), float(eth_price)
def get_all_tickers_view(request): '''Parameters: symbol (str) – Name of symbol pair e.g BNBBTC ''' if request.method == "POST": cli = Client() data = request.data try: agg = cli.get_all_tickers(**data) return JsonResponse(agg, safe=False) except BinanceAPIException as e: return JsonResponse({"MessageError": e.message}, safe=False)
class Binance: def __init__(self, api_key: str, api_secret: str): self.client = Client(api_key, api_secret) def get_tick(self, symbol: str) -> Tick: return Tick(**self.client.get_ticker(symbol=symbol)) def get_all_tickers(self): tickers = [] for tick in self.client.get_all_tickers(): tickers.append(self.get_tick(tick['symbol'])) return tickers
class exchange: """ 建構式 Args: apiKey (str): API金鑰 apiSecret (str): API密鑰 Returns: void """ def __init__(self, apiKey: str, apiSecret: str): self.client = Client(apiKey, apiSecret) """ 取得當前價格 Args: symbol (str): 要取得價格的標的,例BTCUSDT Returns: float: 當前的價格 """ def getSymbolPrice(self, symbol: str) -> float: prices = self.client.get_all_tickers() num = len(prices) price = 0 for i in range(num): if symbol == prices[i]['symbol']: price = prices[i]['price'] return price """ 進行交易 Args: symbol (str): 要取得價格的標的,例BTCUSDT side (str): 要買進用buy,要賣出用sell quantity (float): 要買進的數量 Returns: str: API response """ def doExchange(self, symbol: str, side: str, quantity: float): sides = {'buy': Client.SIDE_BUY, 'sell': Client.SIDE_SELL} order = self.client.create_test_order(symbol=symbol, side=sides[side], type=Client.ORDER_TYPE_MARKET, quantity=quantity) return order
def get_binance_balance(self, api_key, api_secret): """ :returns: binace balance .. code-block:: python { 'TRX': { 'price_BTC': 0.000001, 'value_BTC': 0.00001, 'free': 10 }, 'NEO': { 'price_BTC': 0.000001, 'value_BTC': 0.00001, 'free': 10 }, 'OMG': { 'price_BTC': 0.000001, 'value_BTC': 0.00001, 'free': 10 }, 'BTC': { 'free': 0.002 } } """ client = Client(api_key, api_secret) # Get account information account = client.get_account() # Filter zero balances my_balance = {} for balance in account['balances']: if float(balance['free']) > 0: my_balance[balance['asset']] = {'free': float(balance['free'])} # Get current prices prices = client.get_all_tickers() # Filter only BTC prices by account assets and calculate total value for price in prices: symbol = price['symbol'] if symbol[-3:] == 'BTC' and symbol[:-3] in my_balance.keys(): my_asset = my_balance[symbol[:-3]] my_asset['price_BTC'] = float(price['price']) my_asset['value_BTC'] = (float(price['price']) * my_asset['free']) return my_balance
def binance(list): binance_api = Keys['binance_key'] binance_secret = Keys['binance_secret'] client = Client(binance_api, binance_secret) prices = client.get_all_tickers() for price in prices: if price['symbol'] in list: y = price['price'] x = float(y) z = 1 / x a = btc() b = a * z return b
def binance_get_all_tickers(chat_id): full_api = getbinanceapi(chat_id)['binance_api'] api_key = full_api.split(':')[0].strip() api_secret = full_api.split(':')[1].strip() client = Client(api_key, api_secret) binance_timesync(client) js_info = [] try: js_info = client.get_all_tickers() #print(js_info) return js_info except Exception as e: print(e) return js_info
class Scraper: def __init__(self): self.api_key = '7tDBYdWpcmbHLSmJJKVd2aCVbzyGwdQ3hDgSfw5MrrXSpjAoufMW5Tkk02W1JiPv' self.api_secret = '98BCmuZh6yFLJUYtJ7WtZtCqiMeNTuauxKfzrRQQ82RNnG01HJdxmuXzxZ5SSnyU' self.client = Client(self.api_key, self.api_secret) def run(self): while True: try: tickers = self.client.get_all_tickers() server_time = self.client.get_server_time()['serverTime'] for t in tickers: if t['symbol'] in ["ETHUSDT", "BTCUSDT"]: models.store_data(int(server_time), float(t['price']), t['symbol']) time.sleep(1) except Exception as e: print(e) def tickers(self): return self.client.get_all_tickers()
def update(self): from binance.client import Client _LOGGER.debug('Fetching data from binance.com') try: client = Client(self._api_key, self._api_secret) prices = client.get_all_tickers() for i in prices: self.data[i['symbol']] = i['price'] _LOGGER.debug("Rates updated to %s", self.data) except: _LOGGER.error('Error fetching data from binance.com') self.data = {} return False
def main(): client = Client(config.api_key, config.api_secret) # Get account information account = client.get_account() # Filter zero balances my_balance = {} for balance in account['balances']: if float(balance['free']) > 0: my_balance[balance['asset']] = {'free': float(balance['free'])} # Get current prices prices = client.get_all_tickers() # Add wallet data from config file ''' wallet = { 'symbol_1': amount, 'symbol_2': amount } ''' for k, v in config.wallet.items(): if k in list(my_balance.keys()): my_balance[k]['free'] = my_balance[k]['free'] + v else: my_balance[k] = {} my_balance[k]['free'] = v # Filter only BTC prices by account assets and calculate total value for price in prices: symbol = price['symbol'] if symbol[-3:] == 'BTC' and symbol[:-3] in list(my_balance.keys()): my_asset = my_balance[symbol[:-3]] my_asset['price'] = price['price'] my_asset['value_BTC'] = (float(price['price']) * my_asset['free']) # Extract labels and values for chart labels = [] values = [] for key, value in my_balance.items(): labels.append(key) if key == 'BTC': values.append(float(value['free'])) else: values.append(value['value_BTC']) plot_pie(values, labels)
def fillSymbols(): BUY_SYMBOLS.clear() client1 = Client(config.api_key1, config.api_secret1) data = client1.get_all_tickers() time.sleep(0.1) for x in data: if x['symbol'][-4:].find("USDT") != -1: if x['symbol'][:-4].find("USD") == -1: for a in BLACKLIST: allOf = True if x['symbol'].find(a) != -1: allOf = False break if allOf: BUY_SYMBOLS.append(x['symbol'])
def buy(): global foundCoin client = Client( 'YOUR API KEY HERE', 'YOUR SECRET KEY HERE') # Sisesta siia oma API key ja Secret API Key balanceDict = client.get_asset_balance(asset='BTC') balance = balanceDict.get('free') # Leiab vabade vahendite summa allPrices = client.get_all_tickers() coinInfo = next(item for item in allPrices if item["symbol"] == "%sBTC" % (foundCoin)) foundPrice = coinInfo.get('price') print('[' + str(dt.now().time()) + ']' + 'Your BTC balance is:' + ' ' + str(balance)) print('[' + str(dt.now().time()) + ']' + 'price is' + ' ' + foundPrice) possibleBuy = float(balance) / float( foundPrice ) * 0.8 # Kordaja määrab, kui palju olemasolevast rahast kasutatakse tehingus possibleBuy = float(round(possibleBuy, 8)) def order(): order = client.create_order(symbol='%sBTC' % (foundCoin), side=Client.SIDE_BUY, type=Client.ORDER_TYPE_MARKET, quantity=possibleBuy) print('[' + str(dt.now().time()) + ']' + 'Placed order for %f %s' % (possibleBuy, foundCoin)) x = 8 while True: try: order() break except: possibleBuy = float(round(possibleBuy, x - 1)) x = x - 1 print( '[' + str(dt.now().time()) + ']' + 'Trying' + ' ' + str(possibleBuy) ) # Erinevad coinid lubavad erinevat täpsust, nii et siin proovib # järjest ebatäpsemat ümardamist. search()