def reset_prices(self, symbols=("BTC"), not_symbols=()): """ param tuple symbols: Symbols to watch param tuple not_symbols: Symbols to exclude """ self.symbols = symbols self.not_symbols = not_symbols self.client = binance_util.make_client() self.prices = self.make_price_dict() self.last_price_time = time.time()
def __init__(self, input_channel: str, binance_client=None): self.input_channel = input_channel self.funds = 0.0 self.start_time = time.time() # this should be set as the time at which the trading starts self.max_buy_timelimit = 60 # this should be set to a "safe" period for buying; for now 1 min self.telegram_client = make_client() if not binance_client: self.binance_client = binance_util.make_client() else: self.binance_client = binance_client @self.telegram_client.on(events.NewMessage(chats=self.input_channel)) async def onNewMessage(event): print("recieved message") message = event.message.message if message.media is not None: await account.set_remaining_amount("BTC") await handle_telegram_image(self.telegram_client.download_media(message=message, file=bytes), self.on_recieve_coin_name), elif (name := util.get_coin_name(event.stringify())): self.on_recieve_coin_name(name)
class TestBinanceAPI(unittest.TestCase): client = binance_util.make_client() def test_credentials(self): global credentials_passed try: with self.assertRaises(BinanceAPIException): order = self.client.create_test_order( symbol="BTCUSDT", side=SIDE_SELL, type=ORDER_TYPE_TAKE_PROFIT, stopPrice=200) order = self.client.create_test_order( symbol="BTCUSDT", side=SIDE_BUY, type=ORDER_TYPE_MARKET, quoteOrderQty=200) self.assertFalse(order, "Order error") credentials_passed = True except BinanceAPIException as e: self.assertFalse(e.message, "Invalid Binance credentials!") #@unittest.skipUnless(credentials_passed, "Skipping because connection to Binance cannot be established") def test_system_time_delay(self): max_iters = 5 diffs = [] print(f"testing system time delay; will take about {max_iters}sec") for _ in range(max_iters): server_time = self.client.get_server_time() diffs.append(int(time.time() * 1000) - server_time['serverTime']) time.sleep(1) avg = sum(diffs) // max_iters self.assertTrue(avg > -700 and avg <= 700, f"Either the system clock is out of sync or connecting to binance takes a long time, value: {avg}")
async def get_changed_coins(self, change_threshold=5.0): """ :returns list: List of Coin dicts {"symbol": str, "price": float} """ try: current_prices = self.client.get_all_tickers() except requests.exceptions.ConnectionError: print("Connection aborted, reconnecting") self.client = binance_util.make_client() return [] percent_diff = lambda old_price, new_price: ( (new_price - old_price) / old_price) * 100 changed = [] for item in current_prices: if self.is_allowed_symbol( item["symbol"]) and (diff := percent_diff( float(self.prices[item["symbol"]]), float( item["price"]))) >= change_threshold: item["change"] = diff item["changed_at"] = time.time() changed.append(item)
import binance_util, threading, time funds = None client = binance_util.make_client() def refresh_funds(name): global funds while True: funds = binance_util.get_remaining_amount_sync(client, name) time.sleep(15) if __name__ == "__main__": to_coin = "BTC" th = threading.Thread(target=refresh_funds, args=(to_coin,), daemon=True) th.start() coin_name = input("Enter coin name: ").upper() if len(coin_name) >= 3: symbol = f"{coin_name}{to_coin}" try: order = binance_util.make_market_buy(client, funds, symbol) except Exception as e: print(f"{e}\n with: {coin_name}") exit() else: print(f"Invalid coin name {coin_name}") exit() import webbrowser webbrowser.open_new_tab(f"https://www.binance.com/en/trade/{coin_name}_{to_coin}")