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 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
def __init__(self): self.env = BinanceEnvironment( api_url='https://dex-asiapacific.binance.org', wss_url='wss://dex.binance.org/api/', hrp='bnb') with open('bnb_real_key.txt', 'r') as f: key = f.readline() # for testing # self.env = BinanceEnvironment.get_testnet_env() # with open('bnb_key.txt', 'r') as f: # key = f.readline() f.close() self.client = HttpApiClient(env=self.env) self.wallet = Wallet(key, env=self.env) self.address = self.wallet.address self.ftx = ccxt.ftx({ 'apiKey': '6p37l5AXOzIgFzfeSzkcuPhuaYcw3GcpJrU83ROy', 'secret': '3SphoJJ6Gl_w5pPPkGmQpKbVGN9oPiUgxqs4ob_H' }) #self.assets = ['USD', 'USDT'] self.assets = ['USD'] self.BNB_BUSD = 'BNB.BUSD-BD1' self.pool = THORChain()
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 __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
def __init__(self): self.env = BinanceEnvironment.get_testnet_env() self.client = HttpApiClient(env=self.env) with open('secret/bnb_key.txt', 'r') as f: key = f.readline() self.wallet = Wallet(key, env=self.env) self.address = self.wallet.address driver_logger.info(f'bnb address: {self.address}')
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')
def test_custom_environment(self): api_url = 'my_api_url' wss_url = 'my_wss_url' hrp = 'my_hrp' env = BinanceEnvironment(api_url, wss_url, hrp) assert env.hrp == hrp assert env.wss_url == wss_url assert env.api_url == api_url
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 __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}")
def __init__(self, key, test=False): self.BUSD = 'BUSD-BD1' self.BNB = 'BNB' self.pairs = [] self.bnb_pairs = {} self.busd_pairs = {} self.api_instance = binance_client.DefaultApi() if test: self.env = BinanceEnvironment.get_testnet_env() self.RUNE = 'RUNE-67C' self.api_instance.api_client.configuration.host = self.env.api_url + '/api' else: self.env = BinanceEnvironment(api_url='https://dex-european.binance.org', wss_url='wss://dex.binance.org/api/', hrp='bnb') self.RUNE = 'RUNE-B1A' binance_logger.info(f'Binance connected to node: {self.env.api_url}') self.client = HttpApiClient(env=self.env) self.wallet = Wallet(private_key=key, env=self.env) self.wallet.reload_account_sequence() self.account_info()
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
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
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)
from binance_chain.environment import BinanceEnvironment from binance_chain.http import HttpApiClient from binance_chain.wallet import Wallet testnet_env = BinanceEnvironment.get_testnet_env() client = HttpApiClient(env=testnet_env) def make_binance_wallet(): wallet = Wallet.create_random_wallet(env=testnet_env) print(wallet.address) print(wallet.private_key) print(wallet.public_key_hex) return wallet.address
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
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 env(self): return BinanceEnvironment.get_testnet_env()
def test_testnet_environment(self): env = BinanceEnvironment.get_testnet_env() assert env.hrp == BinanceEnvironment.TESTNET_ENV['hrp'] assert env.wss_url == BinanceEnvironment.TESTNET_ENV['wss_url'] assert env.api_url == BinanceEnvironment.TESTNET_ENV['api_url']
def ws_env(self, env, listen_address): listen_address = listen_address.replace('http://', 'ws://') listen_address = listen_address.replace('https://', 'wss://') return BinanceEnvironment(env.api_url, listen_address, env.hrp)
config = configparser.ConfigParser() config.read('./stream.conf') loop = None bnb_webhook_url = config['stream']['bnb_webhook_url'] token = config['stream']['bnb_token'] address = config.get('stream', 'bnb_master_address').strip() bnb_api_url = config['stream']['bnb_api_url'] bnb_wss_url = config['stream']['bnb_wss_url'] bnb_hrp_url = config['stream']['bnb_hrp_url'] use_testnet = config['stream'].getboolean('use_testnet') sleep_time = config['stream'].getint('sleep_time') if use_testnet is True: print("Use test net") testnet_env = BinanceEnvironment.get_testnet_env() else: print('Use main net') testnet_env = BinanceEnvironment(api_url=bnb_api_url, wss_url=bnb_wss_url, hrp=bnb_hrp_url) print('bnb_webhook_url: {}, token: {}, address: {}'.format( bnb_webhook_url, token, str(address))) print('bnb_api_url: {}, bnb_wss_url: {}, bnb_hrp_url: {}'.format( bnb_api_url, bnb_wss_url, bnb_hrp_url)) headers = { 'content-type': 'application/json', 'Authorization': '', }