def __init__(self, env: Optional[BinanceEnvironment] = None, requests_params: Optional[Dict] = None, **kwargs): """Binance Chain API Client constructor https://binance-chain.github.io/api-reference/dex-api/paths.html :param env: (optional) A BinanceEnvironment instance or None which will default to production env :param requests_params: (optional) Dictionary of requests params to use for all calls :type requests_params: dict. .. code:: python # get production env client prod_client = Client() # get testnet env client testnet_env = BinanceEnvironment.get_testnet_env() client = Client(testnet_env) """ self._env = env or BinanceEnvironment.get_production_env() self._requests_params = requests_params self.session = self._init_session(**kwargs)
async def create(cls, client: HttpApiClient, loop, symbol: str, coro=None, refresh_interval: int = _default_refresh, env: Optional[BinanceEnvironment] = None): """Create a DepthCacheManager instance :param client: Binance API client :param loop: :param symbol: Symbol to create depth cache for :param coro: Optional coroutine to receive depth cache updates :type coro: async coroutine :param env: Optional coroutine to receive depth cache updates :param refresh_interval: Optional number of seconds between cache refresh, use 0 or None to disable """ self = DepthCacheManager() self._client = client self._loop = loop self._symbol = symbol self._coro = coro self._last_update_id = None self._depth_message_buffer = [] self._bm = None self._depth_cache = DepthCache(self._symbol) self._refresh_interval = refresh_interval self._env = env or BinanceEnvironment.get_production_env() await self._start_socket() await self._init_cache() return self
def set_network(self, network: str): """Set/update the current network :param network: "mainnet" or "testnet" :type network: str :returns: the client :raises: raises if network not provided :raises: `Invalid network' if the given network is invalid """ if not network: raise Exception("Network must be provided") else: self.network = network # choose network (testnet or mainnet) if self.network == 'testnet': # initialise with Testnet environment self.env = BinanceEnvironment.get_testnet_env() elif self.network == 'mainnet': # initialise with mainnet environment self.env = BinanceEnvironment.get_production_env() else: raise Exception("Invalid network") self.client = AsyncHttpApiClient(env=self.env) self.address = '' return self.client
def __init__(self, env: Optional[BinanceEnvironment] = None): self._env = env or BinanceEnvironment.get_production_env() self._public_key = None self._address = None self._account_number = None self._sequence = None self._chain_id = None self._http_client = None
async def check_incoming(config): last_stored_time = await Chain.get_last_time(CHAIN_NAME) LOGGER.info("Last time is %s" % last_stored_time) loop = asyncio.get_event_loop() env = BinanceEnvironment.get_production_env() client = AsyncHttpApiClient(env=env) while True: last_stored_time = await Chain.get_last_time(CHAIN_NAME) i = 0 j = 0 tasks = [] seen_ids = [] async for txi in request_transactions(config, client, last_stored_time): i += 1 # TODO: handle big message list stored in IPFS case # (if too much messages, an ipfs hash is stored here). for message in txi['messages']: j += 1 message['time'] = txi['time'] # running those separately... a good/bad thing? # shouldn't do that for VMs. tasks.append( loop.create_task( incoming(message, chain_name=CHAIN_NAME, seen_ids=seen_ids, tx_hash=txi['tx_hash'], height=txi['height'], check_message=True))) # let's join every 500 messages... if (j > 500): for task in tasks: try: await task except Exception: LOGGER.exception("error in incoming task") j = 0 seen_ids = [] tasks = [] for task in tasks: try: await task # let's wait for all tasks to end. except Exception: LOGGER.exception("error in incoming task") # print(i) if (i < 10): # if there was less than 10 items, not a busy time await asyncio.sleep(2)
def test_prod_environment(self): env = BinanceEnvironment() assert env.hrp == BinanceEnvironment.PROD_ENV['hrp'] assert env.wss_url == BinanceEnvironment.PROD_ENV['wss_url'] assert env.api_url == BinanceEnvironment.PROD_ENV['api_url'] prod_env = BinanceEnvironment.get_production_env() assert prod_env.hrp == BinanceEnvironment.PROD_ENV['hrp'] assert prod_env.wss_url == BinanceEnvironment.PROD_ENV['wss_url'] assert prod_env.api_url == BinanceEnvironment.PROD_ENV['api_url']
def __init__(self, wallet_settings: WalletSettings): self._settings = wallet_settings w_env = BinanceEnvironment.get_production_env() if wallet_settings.env_name == 'TESTNET': w_env = BinanceEnvironment.get_testnet_env() self._wallet = Wallet( private_key=wallet_settings.private_key.get_secret_value(), env=w_env) self._http_client: Optional[AsyncHttpApiClient] = None
async def create(cls, loop, callback: Callable[[int], Awaitable[str]], env: Optional[BinanceEnvironment] = None): """Create a BinanceChainSocketManager instance :param loop: asyncio loop :param callback: async callback function to receive messages :param env: :return: """ env = env or BinanceEnvironment.get_production_env() self = WebsocketRpcClient(env=env) self._loop = loop self._callback = callback self._conn = ReconnectingRpcWebsocket(loop, self._recv, env=env) return self
def freeze_bnb_wish(amount): freeze_env = BinanceEnvironment.get_production_env() if NETWORK_SIGN_TRANSACTION_BWISH == 'testnet': freeze_env = BinanceEnvironment.get_testnet_env() client = HttpApiClient(env=freeze_env) bep_wallet = Wallet(BINANCE_PAYMENT_PASSWORD, env=freeze_env) # from settings value = float(amount / 10**18) freeze_msg = TransferMsg(wallet=bep_wallet, symbol=COLD_TOKEN_SYMBOL_BNB, amount=value, to_address=COLD_BNB_ADDRESS, memo='freeze bnb wish') res = client.broadcast_msg(freeze_msg, sync=True) print('result', res, flush=True) if not res[0]['ok']: raise Exception('cannot make bnb wish freeze tx')
async def binance_packer(config): loop = asyncio.get_event_loop() # TODO: testnet perhaps? When we get testnet coins. env = BinanceEnvironment.get_production_env() target_addr = config.binancechain.sync_address.value client = AsyncHttpApiClient(env=env) wallet = Wallet(config.binancechain.private_key.value, env=env) LOGGER.info("BNB Connector set up with address %s" % wallet.address) try: await loop.run_in_executor(None, wallet.reload_account_sequence) except KeyError: pass i = 0 while True: if (i >= 100): try: await loop.run_in_executor(None, wallet.reload_account_sequence) except KeyError: pass # utxo = await get_utxo(config, address) i = 0 messages = [ message async for message in (await Message.get_unconfirmed_raw( limit=500, for_chain=CHAIN_NAME)) ] if len(messages): content = await get_chaindata(messages, bulk_threshold=0) content = json.dumps(content) tx = await loop.run_in_executor(None, prepare_transfer_tx, wallet, target_addr, content.encode('utf-8')) # tx_hash = await tx.get_hash() LOGGER.info("Broadcasting TX") await client.broadcast_msg(tx, sync=True) await asyncio.sleep(35) i += 1
def __init__(self, wallet_settings: WalletSettings): self._settings = wallet_settings w_env = BinanceEnvironment.get_production_env() if wallet_settings.env_name == 'TESTNET': w_env = BinanceEnvironment.get_testnet_env() if wallet_settings.private_key: log_init_type = 'private_key' self._wallet = Wallet(private_key=wallet_settings.private_key.get_secret_value(), env=w_env) elif wallet_settings.mnemonic: log_init_type = 'mnemonic' self._wallet = Wallet.create_wallet_from_mnemonic(wallet_settings.mnemonic.get_secret_value(), env=w_env) else: raise Exception(f"Unable to initialise wallet {wallet_settings.name} no private_key or mnemonic set") self._http_client: Optional[AsyncHttpApiClient] = None logging.info(f"Initialised wallet {wallet_settings.name} with {log_init_type}")
async def check_incoming(config): last_stored_time = await Chain.get_last_time(CHAIN_NAME) LOGGER.info("Last time is %s" % last_stored_time) loop = asyncio.get_event_loop() env = BinanceEnvironment.get_production_env() client = AsyncHttpApiClient(env=env) while True: last_stored_time = await Chain.get_last_time(CHAIN_NAME) i = 0 j = 0 async for jdata, context in request_transactions( config, client, last_stored_time): await incoming_chaindata(jdata, context) await Chain.set_last_time( CHAIN_NAME, datetime.fromtimestamp(context['time'], tz=pytz.utc)) # print(i) if (i < 10): # if there was less than 10 items, not a busy time await asyncio.sleep(2)
end = time.time() print("time :" + str(end - start)) real_total += quantity asyncio.sleep(1) except Exception as e: print("start_order error:") print(e) break await cli.session.close() print("real_total: " + str(real_total)) return True if __name__ == "__main__": test_env = BinanceEnvironment.get_testnet_env() master_env = BinanceEnvironment.get_production_env() private_key_str = "c5b07f6a2f2794521a954e519093e98d768f24ca80675d192ff1d90e6fc055c3" symbol2 = "ANN-457_BNB" main_net_address = "bnb1ewt0w4z4zfnjvmvnqg5fvl35lvp364yk7rhs8l" main_net_private_key_str = "a2ef355c3d1c58851f84ef7476239db8939434b6c89ad946a94ebdf438037c68" symbol1 = "COS-2E4_BNB" loop = asyncio.get_event_loop() hyf = Hyf(loop=loop, env=master_env, private_key_string=main_net_private_key_str, symbol=symbol1) loop.run_until_complete(hyf.start_order(200, 10)) loop.close()
def __init__(self, dongle, env: Optional[BinanceEnvironment] = None): self._dongle = dongle self._path = LedgerApp.HD_PATH self._env = env or BinanceEnvironment.get_production_env() self._hrp = self._env.hrp