{"id":17641329,"url":"https://github.com/mchardysam/python-binance-chain","last_synced_at":"2025-04-05T20:08:08.635Z","repository":{"id":37743123,"uuid":"172324144","full_name":"mchardysam/python-binance-chain","owner":"mchardysam","description":"Binance Chain Exchange API python implementation for automated trading","archived":false,"fork":false,"pushed_at":"2023-04-29T03:08:35.000Z","size":187,"stargazers_count":305,"open_issues_count":30,"forks_count":129,"subscribers_count":24,"default_branch":"master","last_synced_at":"2025-03-29T19:06:10.116Z","etag":null,"topics":["api","binance","client","cryptocurrency","dex","ledger","ledger-wallet","python","python3","rpc","websocket"],"latest_commit_sha":null,"homepage":"http://python-binance-chain.rtfd.io","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mchardysam.png","metadata":{"files":{"readme":"README.rst","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2019-02-24T10:29:29.000Z","updated_at":"2025-03-05T18:02:22.000Z","dependencies_parsed_at":"2024-01-15T13:35:53.935Z","dependency_job_id":null,"html_url":"https://github.com/mchardysam/python-binance-chain","commit_stats":{"total_commits":115,"total_committers":6,"mean_commits":"19.166666666666668","dds":0.07826086956521738,"last_synced_commit":"19d7d639cc912a27ec86831338c2a2dc96289d50"},"previous_names":["mchardysam/python-binance-chain","sammchardy/python-binance-chain"],"tags_count":25,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mchardysam%2Fpython-binance-chain","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mchardysam%2Fpython-binance-chain/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mchardysam%2Fpython-binance-chain/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mchardysam%2Fpython-binance-chain/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mchardysam","download_url":"https://codeload.github.com/mchardysam/python-binance-chain/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247393570,"owners_count":20931813,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","binance","client","cryptocurrency","dex","ledger","ledger-wallet","python","python3","rpc","websocket"],"created_at":"2024-10-23T07:02:08.350Z","updated_at":"2025-04-05T20:08:08.609Z","avatar_url":"https://github.com/mchardysam.png","language":"Python","readme":"=======================================\nWelcome to python-binance-chain v0.1.20\n=======================================\n\n.. image:: https://img.shields.io/pypi/v/python-binance-chain.svg\n    :target: https://pypi.python.org/pypi/python-binance-chain\n\n.. image:: https://img.shields.io/pypi/l/python-binance-chain.svg\n    :target: https://pypi.python.org/pypi/python-binance-chain\n\n.. image:: https://img.shields.io/travis/sammchardy/python-binance-chain.svg\n    :target: https://travis-ci.org/sammchardy/python-binance-chain\n\n.. image:: https://img.shields.io/coveralls/sammchardy/python-binance-chain.svg\n    :target: https://coveralls.io/github/sammchardy/python-binance-chain\n\n.. image:: https://img.shields.io/pypi/wheel/python-binance-chain.svg\n    :target: https://pypi.python.org/pypi/python-binance-chain\n\n.. image:: https://img.shields.io/pypi/pyversions/python-binance-chain.svg\n    :target: https://pypi.python.org/pypi/python-binance-chain\n\nThis is an unofficial Python3 wrapper for the `Binance Chain API \u003chttps://binance-chain.github.io/api-reference/dex-api/paths.html\u003e`_. I am in no way affiliated with Binance, use at your own risk.\n\n\nPyPi\n  https://pypi.python.org/pypi/python-binance-chain\n\nSource code\n  https://github.com/sammchardy/python-binance-chain\n\n\nFeatures\n--------\n\n- Support for Testnet and Production `environments \u003c#environments\u003e`_, along with user defined environment\n- HTTP API `sync \u003c#quick-start\u003e`_ and `async \u003c#async-http-client\u003e`_ implementations\n- `Async Websockets \u003c#websockets\u003e`_ with auto-reconnection and backoff retry algorithm\n- HTTP RPC Node `sync \u003c#node-rpc-http\u003e`_ and `async \u003c#node-rpc-http-async\u003e`_ implementations\n- Advanced async `Pooled HTTP RPC Node client \u003c#pooled-node-rpc-client\u003e`_ spreading requests over available peers\n- `Async Node RPC Websockets \u003c#node-rpc-websockets\u003e`_ with auto-reconnection and backoff retry algorithm\n- `Wallet \u003c#wallet\u003e`_ creation from private key or mnemonic or new wallet with random mnemonic\n- Wallet handling account sequence for transactions\n- Broadcast Transactions over `HTTP \u003c#broadcast-messages-on-httpapiclient\u003e`_ and `RPC \u003c#node-rpc-http\u003e`_ with helper classes for limit buy and sell\n- `Sign transactions \u003c#sign-transaction\u003e`_ and use the signed message how you want\n- `Ledger hardware wallet \u003c#ledger\u003e`_ device (Ledger Blue, Nano S \u0026 Nano X) support for signing messages\n- Async `Depth Cache \u003c#depth-cache\u003e`_ to keep a copy of the order book locally\n- `Signing Service Support \u003c#signing-service\u003e`_ for `binance-chain-signing-service \u003chttps://github.com/sammchardy/binance-chain-signing-service\u003e`_\n- Support for HTTP and HTTPS proxies and to override `Requests and AioHTTP settings \u003crequests-and-aiohttp-settings\u003e`_\n- `UltraJson \u003chttps://github.com/esnme/ultrajson\u003e`_ the ultra fast JSON parsing library for efficient message handling\n- Strong Python3 typing to reduce errors\n- pytest `test suite \u003c#running-tests\u003e`_\n- Response exception handling\n\nRead the `Changelog \u003chttps://python-binance-chain.readthedocs.io/en/latest/changelog.html\u003e`_\n\n\nRecommended Resources\n---------------------\n\n- `Binance Chain Forum \u003chttps://community.binance.org/\u003e`_\n- `Binance Chain Telegram \u003chttps://t.me/BinanceDEXchange\u003e`_\n- `Binance Chain API \u003chttps://binance-chain.github.io/\u003e`_\n- `Tendermint Docs \u003chttps://tendermint.com/docs/\u003e`_\n- `Get Testnet Funds \u003chttps://www.binance.vision/tutorials/binance-dex-funding-your-testnet-account\u003e`_\n\n\nQuick Start\n-----------\n\n.. code:: bash\n\n    pip install python-binance-chain\n\nIf having issues with secp256k1 check the `Installation instructions for the sec256k1-py library \u003chttps://github.com/ludbb/secp256k1-py#installation\u003e`_\n\nIf using the production server there is no need to pass the environment variable.\n\n.. code:: python\n\n    from binance_chain.http import HttpApiClient\n    from binance_chain.constants import KlineInterval\n    from binance_chain.environment import BinanceEnvironment\n\n    # initialise with Testnet environment\n    testnet_env = BinanceEnvironment.get_testnet_env()\n    client = HttpApiClient(env=testnet_env)\n\n    # Alternatively pass no env to get production\n    prod_client = HttpApiClient()\n\n    # connect client to different URL using custom environments, see below\n\n    # get node time\n    time = client.get_time()\n\n    # get node info\n    node_info = client.get_node_info()\n\n    # get validators\n    validators = client.get_validators()\n\n    # get peers\n    peers = client.get_peers()\n\n    # get account\n    account = client.get_account('tbnb185tqzq3j6y7yep85lncaz9qeectjxqe5054cgn')\n\n    # get account sequence\n    account_seq = client.get_account_sequence('tbnb185tqzq3j6y7yep85lncaz9qeectjxqe5054cgn')\n\n    # get markets\n    markets = client.get_markets()\n\n    # get fees\n    fees = client.get_fees()\n\n    # get order book\n    order_book = client.get_order_book('NNB-0AD_BNB')\n\n    # get klines\n    klines = client.get_klines('NNB-338_BNB', KlineInterval.ONE_DAY)\n\n    # get closed orders\n    closed_orders = client.get_closed_orders('tbnb185tqzq3j6y7yep85lncaz9qeectjxqe5054cgn')\n\n    # get open orders\n    open_orders = client.get_open_orders('tbnb185tqzq3j6y7yep85lncaz9qeectjxqe5054cgn')\n\n    # get ticker\n    ticker = client.get_ticker('NNB-0AD_BNB')\n\n    # get trades\n    trades = client.get_trades(limit=2)\n\n    # get order\n    order = client.get_order('9D0537108883C68B8F43811B780327CE97D8E01D-2')\n\n    # get trades\n    trades = client.get_trades()\n\n    # get transactions\n    transactions = client.get_transactions(address='tbnb1n5znwyygs0rghr6rsydhsqe8e6ta3cqatucsqp')\n\n    # get transaction\n    transaction = client.get_transaction('95DD6921370D74D0459590268B439F3DD49F6B1D090121AFE4B2183C040236F3')\n\nSee `API \u003chttps://python-binance-chain.readthedocs.io/en/latest/binance-chain.html#module-binance_chain\u003e`_ docs for more information.\n\nAsync HTTP Client\n-----------------\n\nAn implementation of the HTTP Client above using aiohttp instead of requests\n\nUse the async `create` classmethod to initialise an instance of the class.\n\nAll methods are otherwise the same as the HttpApiClient\n\n\n.. code:: python\n\n    from binance_chain.http import AsyncHttpApiClient\n    from binance_chain.environment import BinanceEnvironment\n    import asyncio\n\n    loop = None\n\n    async def main():\n        global loop\n\n        env = BinanceEnvironment.get_testnet_env()\n\n        # initialise the class using the classmethod\n        client = await AsyncHttpApiClient.create(env)\n        wallet = Wallet(private_key=priv_key, env=env)\n\n        print(json.dumps(await client.get_time(), indent=2))\n\n        while True:\n            print(\"doing a sleep\")\n            await asyncio.sleep(20, loop=loop)\n\n\n    if __name__ == \"__main__\":\n\n        loop = asyncio.get_event_loop()\n        loop.run_until_complete(main())\n\n\nEnvironments\n------------\n\nBinance Chain offers a Production system and Testnet.\n\nIf using the Production system there is no need to pass an environment as this is the default.\n\nTo create and use the Testnet environment is as easy as\n\n.. code:: python\n\n    from binance_chain.environment import BinanceEnvironment\n\n    # initialise with Testnet environment\n    testnet_env = BinanceEnvironment.get_testnet_env()\n\nYou may also create your own custom environments, this may be useful such as connecting to a Node RPC client\n\n.. code:: python\n\n    from binance_chain.environment import BinanceEnvironment\n\n    # create custom environment\n    my_env = BinanceEnvironment(api_url=\"\u003capi_url\u003e\", wss_url=\"\u003cwss_url\u003e\", hrp=\"\u003chrp\u003e\")\n\n\nSee `API \u003chttps://python-binance-chain.readthedocs.io/en/latest/binance-chain.html#module-binance_chain.environment\u003e`_ docs for more information.\n\nWallet\n------\n\nSee `API \u003chttps://python-binance-chain.readthedocs.io/en/latest/binance-chain.html#module-binance_chain.wallet\u003e`_ docs for more information.\n\nThe wallet is required if you want to place orders, transfer funds or freeze and unfreeze tokens.\n\nYou may also use the `Ledger Wallet class \u003c#ledger\u003e`_ to utilise your Ledger Hardware Wallet for signing.\n\nIt can be initialised with your private key or your mnemonic phrase.\n\nYou can additionally provide BIP39 passphrase and derived wallet id.\n\nNote that the BinanceEnvironment used for the wallet must match that of the HttpApiClient, testnet addresses will not\nwork on the production system.\n\nThe Wallet class can also create a new account for you by calling the `Wallet.create_random_wallet()` function,\nsee examples below\n\n\n**Initialise from Private Key**\n\n.. code:: python\n\n    from binance_chain.wallet import Wallet\n    from binance_chain.environment import BinanceEnvironment\n\n    testnet_env = BinanceEnvironment.get_testnet_env()\n    wallet = Wallet('private_key_string', env=testnet_env)\n    print(wallet.address)\n    print(wallet.private_key)\n    print(wallet.public_key_hex)\n\n**Initialise from Mnemonic**\n\n.. code:: python\n\n    from binance_chain.wallet import Wallet\n    from binance_chain.environment import BinanceEnvironment\n\n    testnet_env = BinanceEnvironment.get_testnet_env()\n    wallet = Wallet.create_wallet_from_mnemonic('mnemonic word string',\n                                                 passphrase='optional passphrase',\n                                                 child=0,\n                                                 env=testnet_env)\n    print(wallet.address)\n    print(wallet.private_key)\n    print(wallet.public_key_hex)\n\n**Initialise by generating a random Mneomonic**\n\n.. code:: python\n\n    from binance_chain.wallet import Wallet\n    from binance_chain.environment import BinanceEnvironment\n\n    testnet_env = BinanceEnvironment.get_testnet_env(, env=testnet_env)\n    wallet = Wallet.create_random_wallet(env=env)\n    print(wallet.address)\n    print(wallet.private_key)\n    print(wallet.public_key_hex)\n\nBroadcast Messages on HttpApiClient\n-----------------------------------\n\nSee `API \u003chttps://python-binance-chain.readthedocs.io/en/latest/binance-chain.html#module-binance_chain.messages\u003e`_ docs for more information.\n\nRequires a Wallet to have been created.\n\nThe Wallet will increment the request sequence when broadcasting messages through the HttpApiClient.\n\nIf the sequence gets out of sync call `wallet.reload_account_sequence(client)`, where client is an instance of HttpApiClient.\n\n**Place Order**\n\nGeneral case\n\n.. code:: python\n\n    from binance_chain.http import HttpApiClient\n    from binance_chain.messages import NewOrderMsg\n    from binance_chain.wallet import Wallet\n    from binance_chain.constants import TimeInForce, OrderSide, OrderType\n    from decimal import Decimal\n\n    wallet = Wallet('private_key_string')\n    client = HttpApiClient()\n\n    # construct the message\n    new_order_msg = NewOrderMsg(\n        wallet=wallet,\n        symbol=\"ANN-457_BNB\",\n        time_in_force=TimeInForce.GOOD_TILL_EXPIRE,\n        order_type=OrderType.LIMIT,\n        side=OrderSide.BUY,\n        price=Decimal(0.000396000),\n        quantity=Decimal(12)\n    )\n    # then broadcast it\n    res = client.broadcast_msg(new_order_msg, sync=True)\n\n**Limit Order Buy**\n\n.. code:: python\n\n    from binance_chain.messages import LimitOrderBuyMsg\n\n    limit_order_msg = LimitOrderBuyMsg(\n        wallet=wallet,\n        symbol='ANN-457_BNB',\n        price=0.000396000,\n        quantity=12\n    )\n\n**Limit Order Sell**\n\n.. code:: python\n\n    from binance_chain.messages import LimitOrderSellMsg\n\n    limit_order_msg = LimitOrderSellMsg(\n        wallet=wallet,\n        symbol='ANN-457_BNB',\n        price=0.000396000,\n        quantity=12\n    )\n\n**Cancel Order**\n\n.. code:: python\n\n    from binance_chain.http import HttpApiClient\n    from binance_chain.messages import CancelOrderMsg\n    from binance_chain.wallet import Wallet\n\n    wallet = Wallet('private_key_string')\n    client = HttpApiClient()\n\n    # construct the message\n    cancel_order_msg = CancelOrderMsg(\n        wallet=wallet,\n        order_id=\"order_id_string\",\n        symbol='ANN-457_BNB',\n    )\n    # then broadcast it\n    res = client.broadcast_msg(cancel_order_msg, sync=True)\n\n\n**Freeze Tokens**\n\n.. code:: python\n\n    from binance_chain.http import HttpApiClient\n    from binance_chain.messages import FreezeMsg\n    from binance_chain.wallet import Wallet\n    from decimal import Decimal\n\n    wallet = Wallet('private_key_string')\n    client = HttpApiClient()\n\n    # construct the message\n    freeze_msg = FreezeMsg(\n        wallet=wallet,\n        symbol='BNB',\n        amount=Decimal(10)\n    )\n    # then broadcast it\n    res = client.broadcast_msg(freeze_msg, sync=True)\n\n\n**Unfreeze Tokens**\n\n.. code:: python\n\n    from binance_chain.http import HttpApiClient\n    from binance_chain.messages import UnFreezeMsg\n    from binance_chain.wallet import Wallet\n    from decimal import Decimal\n\n    wallet = Wallet('private_key_string')\n    client = HttpApiClient()\n\n    # construct the message\n    unfreeze_msg = UnFreezeMsg(\n        wallet=wallet,\n        symbol='BNB',\n        amount=Decimal(10)\n    )\n    # then broadcast it\n    res = client.broadcast_msg(unfreeze_msg, sync=True)\n\n\n**Transfer Tokens**\n\n.. code:: python\n\n    from binance_chain.http import HttpApiClient\n    from binance_chain.messages import TransferMsg\n    from binance_chain.wallet import Wallet\n\n    wallet = Wallet('private_key_string')\n    client = HttpApiClient()\n\n    transfer_msg = TransferMsg(\n        wallet=wallet,\n        symbol='BNB',\n        amount=1,\n        to_address='\u003cto address\u003e',\n        memo='Thanks for the beer'\n    )\n    res = client.broadcast_msg(transfer_msg, sync=True)\n\n**Transfer Multiple Tokens**\n\n.. code:: python\n\n    from binance_chain.http import HttpApiClient\n    from binance_chain.messages import TransferMsg, Transfer\n    from binance_chain.wallet import Wallet\n\n    wallet = Wallet('private_key_string')\n    client = HttpApiClient()\n\n    multi_transfer_msg = TransferMsg(\n        wallet=wallet,\n        transfers=[\n            Transfer(symbol='ETH.B', amount=1),\n            Transfer(symbol='BNB', amount=1),\n        ],\n        to_address='\u003cto address\u003e',\n        memo='Thanks for the beer'\n    )\n    res = client.broadcast_msg(multi_transfer_msg, sync=True)\n\n**Vote for proposal**\n\n.. code:: python\n\n    from binance_chain.http import HttpApiClient\n    from binance_chain.messages import VoteMsg\n    from binance_chain.wallet import Wallet\n    from binance_chain.constants import VoteOption\n\n    wallet = Wallet('private_key_string')\n    client = HttpApiClient()\n\n    vote_msg = VoteMsg(\n        wallet=wallet,\n        proposal_id=1,\n        vote_option=VoteOption.YES\n    )\n    res = client.broadcast_msg(vote_msg, sync=True)\n\n\nSign Transaction\n----------------\n\nIf you want to simply sign a transaction you can do that as well.\n\nThis is a transfer example\n\n.. code:: python\n\n    from binance_chain.messages import TransferMsg, Signature\n    from binance_chain.wallet import Wallet\n\n    wallet = Wallet('private_key_string')\n\n    transfer_msg = TransferMsg(\n        wallet=wallet,\n        symbol='BNB',\n        amount=1,\n        to_address='\u003cto address\u003e'\n    )\n    signed_msg = Signature(transfer_msg).sign()\n\n\n\nWebsockets\n----------\n\nSee `API \u003chttps://python-binance-chain.readthedocs.io/en/latest/binance-chain.html#module-binance_chain.websockets\u003e`_ docs for more information.\n\n.. code:: python\n\n    import asyncio\n\n    from binance_chain.websockets import BinanceChainSocketManager\n    from binance_chain.environment import BinanceEnvironment\n\n    testnet_env = BinanceEnvironment.get_testnet_env()\n\n    address = 'tbnb...'\n    loop = None\n\n    async def main():\n        global loop\n\n        async def handle_evt(msg):\n            \"\"\"Function to handle websocket messages\n            \"\"\"\n            print(msg)\n\n        # connect to testnet env\n        bcsm = await BinanceChainSocketManager.create(loop, handle_evt, address, env=testnet_env)\n\n        # subscribe to relevant endpoints\n        await bcsm.subscribe_orders(address)\n        await bcsm.subscribe_market_depth([\"FCT-B60_BNB\", \"0KI-0AF_BNB\"])\n        await bcsm.subscribe_market_delta([\"FCT-B60_BNB\", \"0KI-0AF_BNB\"])\n        await bcsm.subscribe_trades([\"FCT-B60_BNB\", \"0KI-0AF_BNB\"])\n        await bcsm.subscribe_ticker([\"FCT-B60_BNB\", \"0KI-0AF_BNB\"])\n\n        while True:\n            print(\"sleeping to keep loop open\")\n            await asyncio.sleep(20, loop=loop)\n\n\n    if __name__ == \"__main__\":\n\n        loop = asyncio.get_event_loop()\n        loop.run_until_complete(main())\n\n**Unsubscribe**\n\n.. code:: python\n\n    # with an existing BinanceChainSocketManager instance\n\n    await bcsm.unsubscribe_orders()\n\n    # can unsubscribe from a particular symbol, after subscribing to multiple\n    await bcsm.subscribe_market_depth([\"0KI-0AF_BNB\"])\n\n\n**Close Connection**\n\n.. code:: python\n\n    # with an existing BinanceChainSocketManager instance\n\n    await bcsm.close_connection()\n\n\nNode RPC HTTP\n-------------\n\nSee `API \u003chttps://python-binance-chain.readthedocs.io/en/latest/binance-chain.html#module-binance_chain.node_rpc\u003e`_ docs for more information.\n\nThe binance_chain.http.HttpApiClient has a helper function `get_node_peers()` which returns a list of peers with Node RPC functionality\n\n.. code:: python\n\n    from binance_chain.http import HttpApiClient, PeerType\n    from binance_chain.node_rpc import HttpRpcClient\n\n    httpapiclient = HttpApiClient()\n\n    # get a peer that support node requests\n    peers = httpapiclient.get_node_peers()\n    listen_addr = peers[0]['listen_addr']\n\n    # connect to this peer\n    rpc_client = HttpRpcClient(listen_addr)\n\n    # test some endpoints\n    abci_info = rpc_client.get_abci_info()\n    consensus_state = rpc_client.dump_consensus_state()\n    genesis = rpc_client.get_genesis()\n    net_info = rpc_client.get_net_info()\n    num_unconfirmed_txs = rpc_client.get_num_unconfirmed_txs()\n    status = rpc_client.get_status()\n    health = rpc_client.get_health()\n    unconfirmed_txs = rpc_client.get_unconfirmed_txs()\n    validators = rpc_client.get_validators()\n\n    block_height = rpc_client.get_block_height(10)\n\n\nNode RPC HTTP Async\n-------------------\n\nAn aiohttp implementation of the Node RPC HTTP API.\n\nUse the async `create` classmethod to initialise an instance of the class.\n\nAll methods are the same as the binance_chain.node_rpc.http.HttpRpcClient.\n\n.. code:: python\n\n    from binance_chain.node_rpc.http import AsyncHttpRpcClient\n    from binance_chain.http import AsyncHttpApiClient, PeerType\n    from binance_chain.environment import BinanceEnvironment\n    import asyncio\n\n    loop = None\n\n    async def main():\n        global loop\n\n        testnet_env = BinanceEnvironment.get_testnet_env()\n\n        # create the client using the classmethod\n        http_client = await AsyncHttpApiClient.create(env=testnet_env)\n\n        peers = await http_client.get_node_peers()\n        listen_addr = peers[0]['listen_addr']\n\n        rcp_client = await AsyncHttpRpcClient.create(listen_addr)\n\n        print(json.dumps(await rcp_client.get_abci_info(), indent=2))\n\n        while True:\n            print(\"doing a sleep\")\n            await asyncio.sleep(20, loop=loop)\n\n\n    if __name__ == \"__main__\":\n\n        loop = asyncio.get_event_loop()\n        loop.run_until_complete(main())\n\n\nBroadcast Messages on Node RPC HTTP Client\n------------------------------------------\n\nRequires a Wallet to have been created\n\nThe Wallet will increment the request sequence when broadcasting messages through the HttpApiClient.\n\nIf the sequence gets out of sync call `wallet.reload_account_sequence(client)`, where client is an instance of HttpApiClient.\n\n**Place Order**\n\n.. code:: python\n\n    from binance_chain.node_rpc import HttpRpcClient\n    from binance_chain.messages import LimitOrderBuyMsg\n    from binance_chain.wallet import Wallet\n    from binance_chain.constants import RpcBroadcastRequestType\n\n    wallet = Wallet('private_key_string')\n    rpc_client = HttpRpcClient(listen_addr)\n\n    limit_order_msg = LimitOrderBuyMsg(\n        wallet=wallet,\n        symbol='ANN-457_BNB',\n        price=0.000396000,\n        quantity=12\n    )\n\n    # then broadcast it, by default in synchronous mode\n    res = rpc_client.broadcast_msg(limit_order_msg)\n\n    # alternative async request\n    res = rpc_client.broadcast_msg(new_order_msg, request_type=RpcBroadcastRequestType.ASYNC)\n\n    # or commit request\n    res = rpc_client.broadcast_msg(new_order_msg, request_type=RpcBroadcastRequestType.COMMIT)\n\nOther messages can be constructed similar to examples above\n\nPooled Node RPC Client\n----------------------\n\nThis client connects to all available peer nodes in the network and spreads requests across them.\n\nThis helps reduce API rate limit errors.\n\nThe interface is the same as the above HttpRpcClient and AsyncHttpRpcClient classes for consistency.\n\nRequests can be sent using `asyncio gather \u003chttps://docs.python.org/3/library/asyncio-task.html#asyncio.gather\u003e`_ note to\ncheck the number of clients connected to and not exceed that amount\n\n.. code:: python\n\n    import asyncio\n    from binance_chain.node_rpc.pooled_client import PooledRpcClient\n\n\n    async def main():\n\n        # initialise the client, default production environment\n        client = await PooledRpcClient.create()\n\n        # optionally include an environment\n        testnet_env = BinanceEnvironment.get_testnet_env()\n        client = await PooledRpcClient.create(env=testnet_env)\n\n        # show the number of peers connected with the num_peers property\n        print(f\"Connected to {client.num_peers} peers\")\n\n        # requests can be send in bulk using asyncio gather\n        for i in range(0, 5):\n            res = await asyncio.gather(\n                client.get_abci_info(),\n                client.get_consensus_state(),\n                client.get_net_info(),\n                client.get_status(),\n                client.get_health(),\n            )\n            print(f'{i}: {res}')\n\n        print(await client.get_block(1000))\n\n        print(await client.get_blockchain_info(1000, 2000))\n\n    if __name__ == \"__main__\":\n\n        loop = asyncio.get_event_loop()\n        loop.run_until_complete(main())\n\n\nTo keep the peer connections up to date you may re-initialise the list of peers by calling the `initialise_peers` function\n\n.. code:: python\n\n    client.initialise_peers()\n\n\nNode RPC Websockets\n-------------------\n\nSee `API \u003chttps://python-binance-chain.readthedocs.io/en/latest/binance-chain.html#module-binance_chain.node_rpc.websockets\u003e`_ docs for more information.\n\nFor subscribe query examples see the `documentation here \u003chttps://docs.binance.org/api-reference/node-rpc.html#631-subscribe\u003e`_\n\n.. code:: python\n\n    import asyncio\n\n    from binance_chain.http import HttpApiClient\n    from binance_chain.environment import BinanceEnvironment\n    from binance_chain.node_rpc.websockets import WebsocketRpcClient\n\n    loop = None\n\n    async def main():\n        global loop\n\n        async def handle_evt(msg):\n            print(msg)\n\n        # find node peers on testnet\n        testnet_env = BinanceEnvironment.get_testnet_env()\n        client = HttpApiClient(testnet_env)\n\n        peers = client.get_node_peers()\n\n        # construct websocket listen address - may not be correct\n        listen_addr = re.sub(r\"^https?:\\/\\/\", \"tcp://\", peers[0]['listen_addr'])\n\n        # create custom environment for RPC Websocket\n        node_env = BinanceEnvironment(\n            api_url=testnet_env.api_url,\n            wss_url=listen_addr,\n            hrp=testnet_env.hrp\n        )\n\n        wrc = await WebsocketRpcClient.create(loop, handle_evt, env=node_env)\n\n        await wrc.subscribe(\"tm.event = 'NewBlock'\")\n        await wrc.abci_info()\n\n        while True:\n            print(\"sleeping to keep loop open\")\n            await asyncio.sleep(20, loop=loop)\n\n\n    if __name__ == \"__main__\":\n\n        loop = asyncio.get_event_loop()\n        loop.run_until_complete(main())\n\n**Unsubscribe**\n\n.. code:: python\n\n    # with an existing WebsocketRpcClient instance\n\n    await wrc.unsubscribe(\"tm.event = 'NewBlock'\")\n\n**Unsubscribe All**\n\n.. code:: python\n\n    # with an existing WebsocketRpcClient instance\n\n    await wrc.unsubscribe_all()\n\n\nDepth Cache\n-----------\n\nFollow the order book for a specified trading pair.\n\nNote: This may not be 100% reliable as the response info available from Binance Chain may not always match up\n\n.. code:: python\n\n\n    from binance_chain.depthcache import DepthCacheManager\n    from binance_chain.environment import BinanceEnvironment\n    from binance_chain.http import HttpApiClient\n\n    dcm = None\n    loop = None\n\n\n    async def main():\n        global dcm1, loop\n\n        async def process_depth(depth_cache):\n            print(\"symbol {}\".format(depth_cache.symbol))\n            print(\"1: top 5 asks\")\n            print(depth_cache.get_asks()[:5])\n            print(\"1: top 5 bids\")\n            print(depth_cache.get_bids()[:5])\n\n        env = BinanceEnvironment.get_testnet_env()\n        client = HttpApiClient(env=env)\n\n        dcm = await DepthCacheManager.create(client, loop, \"100K-9BC_BNB\", process_depth, env=env)\n\n        while True:\n            print(\"doing a sleep\")\n            await asyncio.sleep(20, loop=loop)\n\n\n    if __name__ == \"__main__\":\n\n        loop = asyncio.get_event_loop()\n        loop.run_until_complete(main())\n\n\nSigning Service\n---------------\n\nA Service to sign and optionally also broadcast messages for you.\n\nThe service holds the private keys of the accounts and supplies a username and password to interact with these accounts.\n\nThis client re-uses the binance_chain.messages types. In this case no wallet parameter is required.\n\nThis client interacts with the `binance-chain-signing-service \u003chttps://github.com/sammchardy/binance-chain-signing-service\u003e`_ read the docs there\nto create our own signing service.\n\n**Signing and then broadcasting**\n\n.. code:: python\n\n    from binance_chain.messages import NewOrderMsg\n    from binance_chain.signing.http import HttpApiSigningClient\n    from binance_chain.constants import TimeInForce, OrderSide, OrderType\n\n    signing_client = HttpApiSigningClient('http://localhost:8000', username='sam', password='mypass')\n\n    # print(client.signing_service_auth())\n\n    new_order_msg = NewOrderMsg(\n        symbol='ANN-457_BNB',\n        order_type=OrderType.LIMIT,\n        side=OrderSide.BUY,\n        price=0.000396000,\n        quantity=10,\n        time_in_force=TimeInForce.GOOD_TILL_EXPIRE\n    )\n    new_order_hex = signing_client.sign_order(new_order_msg, wallet_name='wallet_1')\n\nthe `sign_order` method can also take a binance_chain.messages.LimitOrderBuyMsg or binance_chain.messages.LimitOrderSellMsg instance.\n\n\nThis hex can then be broadcast using the normal HTTP Client like so\n\n\n.. code:: python\n\n    from binance_chain.http import HttpApiClient\n    from binance_chain.environment import BinanceEnvironment\n\n    # initialise with environment that is supported by the signing service wallet\n    testnet_env = BinanceEnvironment.get_testnet_env()\n    client = HttpApiClient(env=testnet_env)\n\n    res = client.broadcast_hex_msg(new_order_hex['signed_msg'], sync=True)\n\nThe signing service supports binance_chain.messages types\nNewOrderMsg, CancelOrderMsg, FreezeMsg, UnFreezeMsg and TransferMsg\n\n\n**Signing and broadcasting in one**\n\nTo sign and broadcast an order use the `broadcast_order` method. This returns the response from the Binance Chain exchange.\n\n.. code:: python\n\n    from binance_chain.messages import NewOrderMsg\n    from binance_chain.signing.http import HttpApiSigningClient\n    from binance_chain.constants import TimeInForce, OrderSide, OrderType\n\n    signing_client = HttpApiSigningClient('http://localhost:8000', username='sam', password='mypass')\n\n    # print(client.signing_service_auth())\n\n    new_order_msg = NewOrderMsg(\n        symbol='ANN-457_BNB',\n        order_type=OrderType.LIMIT,\n        side=OrderSide.BUY,\n        price=0.000396000,\n        quantity=10,\n        time_in_force=TimeInForce.GOOD_TILL_EXPIRE\n    )\n    res = signing_client.broadcast_order(new_order_msg, wallet_name='wallet_1')\n\n\nAsync Signing Service\n---------------------\n\nLike all other libraries there is an async version.\n\n.. code:: python\n\n    from binance_chain.signing.http import AsyncHttpApiSigningClient\n    from binance_chain.http import AsyncHttpApiClient, PeerType\n    from binance_chain.environment import BinanceEnvironment\n    from binance_chain.constants import TimeInForce, OrderSide, OrderType\n    import asyncio\n\n    loop = None\n\n    async def main():\n        global loop\n\n        # create the client using the classmethod\n        signing_client = await AsyncHttpApiSigningClient.create('http://localhost:8000', username='sam', password='mypass')\n\n        new_order_msg = NewOrderMsg(\n            symbol='ANN-457_BNB',\n            order_type=OrderType.LIMIT,\n            side=OrderSide.BUY,\n            price=0.000396000,\n            quantity=10,\n            time_in_force=TimeInForce.GOOD_TILL_EXPIRE\n        )\n\n        # simply sign the message\n        sign_res = await signing_client.sign_order(new_order_msg, wallet_name='wallet_1')\n\n        # or broadcast it as well\n        broadcast_res = await signing_client.broadcast_order(new_order_msg, wallet_name='wallet_1')\n\n        print(json.dumps(await rcp_client.get_abci_info(), indent=2))\n\n        while True:\n            print(\"doing a sleep\")\n            await asyncio.sleep(20, loop=loop)\n\n\n    if __name__ == \"__main__\":\n\n        loop = asyncio.get_event_loop()\n        loop.run_until_complete(main())\n\nLedger\n------\n\nSign transactions with your Ledger wallet, supports Ledger Blue, Nano S and Nano X.\n\nMake sure you have registered on Binance Chain with your Ledger address.\n\nMake sure that you have connected your Ledger and are in the Binance Chain app.\n\nInstall python-binance-chain with this optional library like so `pip install python-binance-chain[ledger]`\n\nUses the `btchip-python library \u003chttps://github.com/LedgerHQ/btchip-python\u003e`_ if having issues installing check their github page\n\n.. code:: python\n\n    from binance_chain.ledger import getDongle, LedgerApp, LedgerWallet\n    from binance_chain.environment import BinanceEnvironment\n\n    dongle = getDongle(debug=True)\n\n    testnet_env = BinanceEnvironment.get_testnet_env()\n    app = LedgerApp(dongle, env=testnet_env)\n\n    # get the Ledger Binance app version\n    print(app.get_version())\n\n    # Show your address on the Ledger\n    print(app.show_address())\n\n    # Get your address and public key from the Ledger\n    print(app.get_address())\n\n    # Get your public key from the Ledger\n    print(app.get_public_key())\n\n\nCreate a Wallet to use with the HTTP and Node RPC clients\n\n.. code:: python\n\n    # this will prompt you on your Ledger to confirm the address you want to use\n    wallet = LedgerWallet(app, env=testnet_env)\n\n\n    # now create messages and sign them with this wallet\n    from binance_chain.http import HttpApiClient\n    from binance_chain.messages import NewOrderMsg, OrderType, OrderSide, TimeInForce\n\n    client = HttpApiClient(env=testnet_env)\n    new_order_msg = NewOrderMsg(\n        wallet=wallet,\n        symbol='ANN-457_BNB',\n        order_type=OrderType.LIMIT,\n        side=OrderSide.BUY,\n        price=0.000396000,\n        quantity=10,\n        time_in_force=TimeInForce.GOOD_TILL_EXPIRE\n    )\n    new_order_res = client.broadcast_msg(new_order_msg, sync=True)\n\n    print(new_order_res)\n\n\nRequests and AioHTTP Settings\n-----------------------------\n\n`python-binance-chain` uses `requests \u003chttp://docs.python-requests.org\u003e`_ and `aiohttp \u003chttps://github.com/aio-libs/aiohttp\u003e`_ libraries.\n\nYou can set custom requests parameters for all API calls when creating any of the http clients.\n\n.. code:: python\n\n    client = HttpApiClient(request_params={\"verify\": False, \"timeout\": 20})\n\nCheck out either the `requests documentation \u003chttp://docs.python-requests.org\u003e`_ or `aiohttp documentation \u003chttps://github.com/aio-libs/aiohttp\u003e`_ for all options.\n\n**Proxy Settings**\n\nYou can use the settings method above\n\n.. code:: python\n\n    proxies = {\n        'http': 'http://10.10.1.10:3128',\n        'https': 'http://10.10.1.10:1080'\n    }\n\n    # in the Client instantiation\n    client = HttpApiClient(request_params={'proxies': proxies})\n\nOr set an environment variable for your proxy if required to work across all requests.\n\nAn example for Linux environments from the `requests Proxies documentation \u003chttp://docs.python-requests.org/en/master/user/advanced/#proxies\u003e`_ is as follows.\n\n.. code-block:: bash\n\n    $ export HTTP_PROXY=\"http://10.10.1.10:3128\"\n    $ export HTTPS_PROXY=\"http://10.10.1.10:1080\"\n\nFor Windows environments\n\n.. code-block:: bash\n\n    C:\\\u003eset HTTP_PROXY=http://10.10.1.10:3128\n    C:\\\u003eset HTTPS_PROXY=http://10.10.1.10:1080\n\n\nRunning Tests\n-------------\n\n.. code-block:: bash\n\n    git clone https://github.com/sammchardy/python-binance-chain.git\n    cd python-binance-chain\n    pip install -r test-requirements.txt\n\n    python -m pytest tests/\n\n\nDonate\n------\n\nIf this library helped you out feel free to donate.\n\n- ETH: 0xD7a7fDdCfA687073d7cC93E9E51829a727f9fE70\n- NEO: AVJB4ZgN7VgSUtArCt94y7ZYT6d5NDfpBo\n- LTC: LPC5vw9ajR1YndE1hYVeo3kJ9LdHjcRCUZ\n- BTC: 1Dknp6L6oRZrHDECRedihPzx2sSfmvEBys\n\nThanks\n------\n\n`Sipa \u003chttps://github.com/sipa/bech32\u003e` for python reference implementation for Bech32 and segwit addresses\n\n\nOther Exchanges\n---------------\n\nIf you use `Binance \u003chttps://www.binance.com/?ref=10099792\u003e`_ check out my `python-binance \u003chttps://github.com/sammchardy/python-binance\u003e`_ library.\n\nIf you use `Kucoin \u003chttps://www.kucoin.com/?rcode=E42cWB\u003e`_ check out my `python-kucoin \u003chttps://github.com/sammchardy/python-kucoin\u003e`_ library.\n\nIf you use `IDEX \u003chttps://idex.market\u003e`_ check out my `python-idex \u003chttps://github.com/sammchardy/python-idex\u003e`_ library.\n","funding_links":[],"categories":["Python"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmchardysam%2Fpython-binance-chain","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmchardysam%2Fpython-binance-chain","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmchardysam%2Fpython-binance-chain/lists"}