{"id":20392313,"url":"https://github.com/wiseplat/trading_bot_binance","last_synced_at":"2026-06-05T12:31:01.835Z","repository":{"id":233845310,"uuid":"787897895","full_name":"WISEPLAT/Trading_Bot_Binance","owner":"WISEPLAT","description":"Free, open source crypto trading bot","archived":false,"fork":false,"pushed_at":"2024-04-17T12:06:40.000Z","size":7,"stargazers_count":1,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-10T13:33:42.601Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"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/WISEPLAT.png","metadata":{"files":{"readme":"README.md","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,"dei":null}},"created_at":"2024-04-17T11:50:06.000Z","updated_at":"2025-01-21T17:01:00.000Z","dependencies_parsed_at":"2024-04-17T13:30:59.278Z","dependency_job_id":"6ad6c8ad-bb47-4c5e-863b-b44f10c89e17","html_url":"https://github.com/WISEPLAT/Trading_Bot_Binance","commit_stats":null,"previous_names":["wiseplat/trading_bot_binance"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/WISEPLAT/Trading_Bot_Binance","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WISEPLAT%2FTrading_Bot_Binance","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WISEPLAT%2FTrading_Bot_Binance/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WISEPLAT%2FTrading_Bot_Binance/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WISEPLAT%2FTrading_Bot_Binance/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/WISEPLAT","download_url":"https://codeload.github.com/WISEPLAT/Trading_Bot_Binance/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WISEPLAT%2FTrading_Bot_Binance/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33942426,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-05T02:00:06.157Z","response_time":120,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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":[],"created_at":"2024-11-15T03:43:20.995Z","updated_at":"2026-06-05T12:31:01.812Z","avatar_url":"https://github.com/WISEPLAT.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Crypto Trading Bot for Binance\r\n\r\nThe provided code implements a basic trading strategy using the Backtrader library, focused on buying and selling assets on the Binance exchange. Let's break down the code and discuss its functionality.\r\n\r\nThe code begins by importing necessary modules and libraries: **datetime**, **backtrader**, and the **Binance** extension for Backtrader. Additionally, set your API keys and other settings related to the Binance exchange.\r\n\r\n```shell\r\nimport datetime as dt\r\nimport backtrader as bt\r\nfrom backtrader_binance import BinanceStore\r\n\r\nBINANCE_API_KEY = \"YOUR_BINANCE_API_KEY\"\r\nBINANCE_API_SECRET = \"YOUR_BINANCE_API_SECRET\"\r\n\r\n```\r\n\r\nFollowing the imports, the code defines a trading strategy class named JustBuySellStrategy, which inherits from **bt.Strategy**. This strategy is designed for live trading and performs simple buy and sell actions.\r\n\r\n```commandline\r\nclass JustBuySellStrategy(bt.Strategy):\r\n    \"\"\"\r\n    Live strategy demonstration - just buy and sell\r\n    \"\"\"\r\n    params = (\r\n        ('coin_target', ''),\r\n    )\r\n\r\n```\r\n\r\nThe **__init__** method initializes the strategy and sets up necessary data structures. It creates an empty dictionary orders to store orders for each ticker.\r\n\r\n```commandline\r\ndef __init__(self):\r\n    \"\"\"Initialization, adding indicators for each ticker\"\"\"\r\n    self.orders = {}  # All orders as a dict, for this particularly trading strategy one ticker is one order\r\n    for d in self.datas:  # Running through all the tickers\r\n        self.orders[d._name] = None  # There is no order for ticker yet\r\n\r\n```\r\n\r\nThe next method is where the strategy's main logic resides. It iterates over each data feed (ticker) and checks its status (live or historical). If the data is live, it retrieves relevant information such as open, high, low, close prices, and volume. It also prints out this information along with the data's status.\r\n\r\n```commandline\r\ndef next(self):\r\n    \"\"\"Arrival of a new ticker candle\"\"\"\r\n    for data in self.datas:  # Running through all the requested bars of all tickers\r\n        ticker = data._name\r\n        status = data._state  # 0 - Live data, 1 - History data, 2 - None\r\n        _interval = self.broker._store.get_interval(data._timeframe, data._compression)\r\n\r\n```\r\n\r\nIf the data is live, the strategy checks for existing positions and places buy orders accordingly. It also handles canceling existing orders if necessary.\r\n\r\n```commandline\r\nif status == 0:  # Live trade\r\n    coin_target = self.p.coin_target\r\n    ...\r\n    if not self.getposition(data):  # If there is no position\r\n        ...\r\n        self.orders[data._name] = self.buy(data=data, exectype=bt.Order.Market, size=size)\r\n        print(f\"\\t - The Market order has been submitted {self.orders[data._name].binance_order['orderId']} to buy {data._name}\")\r\n\r\n```\r\n\r\nThe notify_order method is called whenever the status of an order changes. It logs relevant information about the order, such as its status, type (buy or sell), price, and size.\r\n\r\n```commandline\r\ndef notify_order(self, order):\r\n    \"\"\"Changing the status of the order\"\"\"\r\n    order_data_name = order.data._name  # Name of ticker from order\r\n    self.log(f'Order number {order.ref} {order.info[\"order_number\"]} {order.getstatusname()} {\"Buy\" if order.isbuy() else \"Sell\"} {order_data_name} {order.size} @ {order.price}')\r\n\r\n```\r\n\r\nSimilarly, the notify_trade method is called when a trade (position) is closed. It logs information about the profit or loss from the closed position.\r\n\r\n```commandline\r\ndef notify_trade(self, trade):\r\n    \"\"\"Changing the position status\"\"\"\r\n    if trade.isclosed:  # If the position is closed\r\n        self.log(f'Profit on a closed position {trade.getdataname()} Total={trade.pnl:.2f}, No commission={trade.pnlcomm:.2f}')\r\n\r\n```\r\n\r\nLastly, the log method is a utility function to print messages along with timestamps to the console.\r\n\r\n```commandline\r\ndef log(self, txt, dt=None):\r\n    \"\"\"Print string with date to the console\"\"\"\r\n    dt = bt.num2date(self.datas[0].datetime[0]) if not dt else dt  # date or date of the current bar\r\n    print(f'{dt.strftime(\"%d.%m.%Y %H:%M\")}, {txt}')  # Print the date and time with the specified text to the console\r\n\r\n```\r\n\r\nThe main part of the script initializes the Backtrader framework (cerebro), sets up the Binance data store and broker, configures data retrieval for a specific symbol (ETH/USDT), adds the data and strategy to cerebro, and finally runs the strategy.\r\n\r\n```commandline\r\nif __name__ == '__main__':\r\n    cerebro = bt.Cerebro(quicknotify=True)\r\n\r\n    coin_target = 'USDT'  # the base ticker in which calculations will be performed\r\n    symbol = 'ETH' + coin_target  # the ticker by which we will receive data in the format \u003cCodeTickerBaseTicker\u003e\r\n\r\n    store = BinanceStore(\r\n        api_key=Config.BINANCE_API_KEY,\r\n        api_secret=Config.BINANCE_API_SECRET,\r\n        coin_target=coin_target,\r\n        testnet=False)  # Binance Storage\r\n\r\n    # live connection to Binance - for Offline comment these two lines\r\n    broker = store.getbroker()\r\n    cerebro.setbroker(broker)\r\n\r\n    # Historical 1-minute bars for the last hour + new live bars / timeframe M1\r\n    from_date = dt.datetime.utcnow() - dt.timedelta(minutes=5)\r\n    data = store.getdata(timeframe=bt.TimeFrame.Minutes, compression=1, dataname=symbol, start_date=from_date, LiveBars=True)\r\n\r\n    cerebro.adddata(data)  # Adding data\r\n\r\n    cerebro.addstrategy(JustBuySellStrategy, coin_target=coin_target)  # Adding a trading system\r\n\r\n    cerebro.run()  # Launching a trading system\r\n    cerebro.plot()  # Draw a chart\r\n\r\n```\r\n\r\nIn summary, the code demonstrates a simple live trading strategy using Backtrader and Binance API for data retrieval and trading execution. It buys assets based on certain conditions and logs relevant information about orders, trades, and positions.\r\n\r\n## License\r\n[MIT](https://choosealicense.com/licenses/mit)\r\n\r\n## Important\r\nError correction, revision and development of the library is carried out by the author and the community!\r\n\r\n**Push your commits!**\r\n\r\n## Terms of Use\r\nThe backtrader_binance library, which allows you to integrate Backtrader and Binance API, is the **Program** created solely for the convenience of work.\r\nWhen using the **Program**, the User is obliged to comply with the provisions of the current legislation of his country.\r\nUsing the **Program** are offered on an \"AS IS\" basis. No guarantees, either oral or written, are attached and are not provided.\r\nThe author and the community does not guarantee that all errors of the **Program** have been eliminated, respectively, the author and the community do not bear any responsibility for\r\nthe consequences of using the **Program**, including, but not limited to, any damage to equipment, computers, mobile devices,\r\nUser software caused by or related to the use of the **Program**, as well as for any financial losses\r\nincurred by the User as a result of using the **Program**.\r\nNo one is responsible for data loss, losses, damages, including accidental or indirect, lost profits, loss of revenue or any other losses\r\nrelated to the use of the **Program**.\r\n\r\nThe **Program** is distributed under the terms of the [MIT](https://choosealicense.com/licenses/mit ) license.\r\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwiseplat%2Ftrading_bot_binance","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwiseplat%2Ftrading_bot_binance","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwiseplat%2Ftrading_bot_binance/lists"}