├── .env.example ├── .gitignore ├── Procfile ├── README.en.md ├── README.md ├── demo ├── demo0.png ├── demo1.png └── demo2.png ├── main.py ├── requirements.txt ├── runtime.txt └── src ├── __init__.py ├── logger.py └── trading.py /.env.example: -------------------------------------------------------------------------------- 1 | API_KEY = 2 | API_SECRET_KEY = 3 | PASSPHRASE = 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | .DS_Store 3 | */.DS_Store 4 | logs 5 | *.log 6 | npm-debug.log* 7 | yarn-debug.log* 8 | yarn-error.log* 9 | lerna-debug.log* 10 | 11 | # Diagnostic reports (https://nodejs.org/api/report.html) 12 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 13 | 14 | # Runtime data 15 | pids 16 | *.pid 17 | *.seed 18 | *.pid.lock 19 | 20 | # Directory for instrumented libs generated by jscoverage/JSCover 21 | lib-cov 22 | 23 | # Coverage directory used by tools like istanbul 24 | coverage 25 | *.lcov 26 | 27 | # nyc test coverage 28 | .nyc_output 29 | 30 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 31 | .grunt 32 | 33 | # Bower dependency directory (https://bower.io/) 34 | bower_components 35 | 36 | # node-waf configuration 37 | .lock-wscript 38 | 39 | # Compiled binary addons (https://nodejs.org/api/addons.html) 40 | build/Release 41 | 42 | # Dependency directories 43 | node_modules/ 44 | jspm_packages/ 45 | 46 | # Snowpack dependency directory (https://snowpack.dev/) 47 | web_modules/ 48 | 49 | # TypeScript cache 50 | *.tsbuildinfo 51 | 52 | # Optional npm cache directory 53 | .npm 54 | 55 | # Optional eslint cache 56 | .eslintcache 57 | 58 | # Microbundle cache 59 | .rpt2_cache/ 60 | .rts2_cache_cjs/ 61 | .rts2_cache_es/ 62 | .rts2_cache_umd/ 63 | 64 | # Optional REPL history 65 | .node_repl_history 66 | 67 | # Output of 'npm pack' 68 | *.tgz 69 | 70 | # Yarn Integrity file 71 | .yarn-integrity 72 | 73 | # dotenv environment variables file 74 | .env 75 | .env.test 76 | 77 | # parcel-bundler cache (https://parceljs.org/) 78 | .cache 79 | .parcel-cache 80 | 81 | # Next.js build output 82 | .next 83 | out 84 | 85 | # Nuxt.js build / generate output 86 | .nuxt 87 | dist 88 | 89 | # Gatsby files 90 | .cache/ 91 | # Comment in the public line in if your project uses Gatsby and not Next.js 92 | # https://nextjs.org/blog/next-9-1#public-directory-support 93 | # public 94 | 95 | # vuepress build output 96 | .vuepress/dist 97 | 98 | # Serverless directories 99 | .serverless/ 100 | 101 | # FuseBox cache 102 | .fusebox/ 103 | 104 | # DynamoDB Local files 105 | .dynamodb/ 106 | 107 | # TernJS port file 108 | .tern-port 109 | 110 | # Stores VSCode versions used for testing VSCode extensions 111 | .vscode-test 112 | 113 | # yarn v2 114 | .yarn/cache 115 | .yarn/unplugged 116 | .yarn/build-state.yml 117 | .yarn/install-state.gz 118 | .pnp.* -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: python main.py -------------------------------------------------------------------------------- /README.en.md: -------------------------------------------------------------------------------- 1 | # ChatGPT Trading Bot 2 | 3 | [中文](README.md) | English 4 | 5 | [![license](https://img.shields.io/pypi/l/ansicolortags.svg)](LICENSE) [![Release](https://img.shields.io/github/v/release/TheExplainthis/ChatGPT-Trading-Bot)](https://github.com/TheExplainthis/ChatGPT-Trading-Bot/releases/) 6 | 7 | 8 | ![Demo](https://github.com/TheExplainthis/ChatGPT-Trading-Bot/blob/main/demo/demo0.png) 9 | 10 | This repository teaches you how to use ChatGPT to help you write trading programs and deploy the code to Heroku to achieve automated trading. The exchange used for this article is Binance, but if you have other trading platforms, you can connect them yourself. 11 | 12 | ## ChatGPT Training Method 13 | 14 | 1. First, I asked NotionAI to come up with ten possible trading strategies for me, as follows: 15 | - A momentum trading strategy based on price and volume data 16 | - A mean reversion strategy using Bollinger Bands and RSI indicators 17 | - A trend following strategy using moving averages and MACD indicator 18 | - A breakout trading strategy based on support and resistance levels 19 | - A pairs trading strategy using cointegration analysis 20 | - A news-based trading strategy using sentiment analysis on financial news 21 | - An arbitrage trading strategy using cross-market analysis 22 | - A swing trading strategy using candlestick patterns and chart analysis 23 | - A quantitative trading strategy based on statistical models and machine learning algorithms 24 | - A position trading strategy using fundamental analysis and value investing principles 25 | 2. Tell ChatGPT like this: `Give me pipescript code with version 4 running on TradingView for {trading strategy}`, so an example is as follows: 26 | ``` 27 | Give me pipescript code with version 4 running on TradingView for A momentum trading strategy based on price and volume data. 28 | ``` 29 | 3. Copy the ChatGPT code, some parts need to be adjusted 30 | - For the second line of the code, sometimes ChatGPT will give you `study` and you need to change it to `strategy`. 31 | - Sometimes for the entry/exit code, he will give you the following code, which needs to be modified to trigger during backtesting: 32 | ```python 33 | if buy_signal 34 | alert("Buy Signal") 35 | if sell_signal 36 | alert("Sell Signal") 37 | ``` 38 | - Modify it to the following code: 39 | ```python 40 | if buy_signal 41 | strategy.entry("Buy", strategy.long) 42 | if sell_signal 43 | strategy.entry("Sell", strategy.short) 44 | ``` 45 | - Add the parameter `alert_message` after Buy, Sell, Buy Exit, and Sell Exit, so that the subsequent Notification setup won't go wrong. 46 | ```python 47 | if long_bb and long_ma and macd_above_signal and time >= start_time 48 | strategy.entry("Buy", strategy.long, alert_message="Buy") 49 | if short_bb and short_ma and macd_below_signal and time >= start_time 50 | strategy.entry("Sell", strategy.short, alert_message="Sell") 51 | 52 | if exit_bb or exit_ma 53 | strategy.exit('Buy Exit', 'Buy', alert_message="Buy_Exit") 54 | strategy.exit('Sell Exit', 'Sell', alert_message="Sell_Exit") 55 | 56 | ``` 57 | > Note: Sometimes the code provided by ChatGPT may not work, so you can ask him multiple times or provide him with the error message. 58 | 4. Adjust the parameters to get the best results, as shown in the figure below: 59 | 60 | ![Demo](https://github.com/TheExplainthis/ChatGPT-Trading-Bot/blob/main/demo/demo1.png) 61 | 62 | 63 | ## Automated Installation Steps 64 | ### Token Acquisition 65 | 1. Log in to [Binance](https://www.binance.com/en) 66 | 2. On the left side after logging in, there is an `API Management` option. Click on it and then click `Create` in the upper right corner. 67 | 3. You will then receive an `API Key` and `Secret Key`. 68 | 69 | ### Project Setup 70 | 1. Fork Github repository: 71 | 1. Register/Login to [GitHub](https://github.com/). 72 | 2. Go to [ChatGPT-Trading-Bot](https://github.com/TheExplainthis/ChatGPT-Trading-Bot). 73 | 3. Click `Star` to support the developer. 74 | 4. Click `Fork` to copy all the code to your own repository. 75 | 2. Space deployment registration (free space): 76 | 1. Register/Login to [Heroku](https://www.heroku.com/). 77 | 2. In the upper right corner, click `New` -> `Create new app`. 78 | 3. App Name: `Enter the App name`, `Region`: `Europe`. 79 | 4. Click `Create app`. 80 | 81 | ### Project Execution 82 | 1. Environment Variable Configuration 83 | 1. Click on `Settings` -> `Reveal Config Vars` 84 | 2. Add environment variables, that include: 85 | 1. API Key: 86 | - key: `API_KEY` 87 | - value: `[obtained from step one above]` 88 | 2. API SECRET KEY: 89 | - key: `API_SECRET_KEY` 90 | - value: `[obtained from step one above]` 91 | 3. PASSPHRASE -> Used as a Token when TradingView sends a Request to the Server to avoid making the API available to everyone. 92 | - key: `PASSPHRASE` 93 | - value: `User-generated, will be used in step four` 94 | 2. Deployment Steps 95 | 1. Enter the folder where `ChatGPT-Trading-Bot` is located using the Terminal 96 | 2. Check if the folder is the same as the following with `ls` 97 | ``` 98 | Procfile 99 | demo 100 | src 101 | main.py 102 | runtime.txt 103 | README.md 104 | README.en.md 105 | requirements.txt 106 | ``` 107 | 3. Install [Heroku cli](https://devcenter.heroku.com/articles/heroku-cli#install-the-heroku-cli) 108 | 4. Deploy, refer to the process in the Deploy page below 109 | - Log in to Heroku, enter in the Terminal: 110 | ``` 111 | $ heroku login 112 | ``` 113 | - Add location, enter in the Terminal: 114 | ``` 115 | $ heroku git:remote -a [Your App Name] 116 | ``` 117 | 5. Push the repo to Heroku, enter in the Terminal: 118 | ``` 119 | $ git push heroku main 120 | ``` 121 | 6. After successful deployment, your URL will be in `Settings` -> `Domains` 122 | 7. After clicking the link, you will see `Hello, World!` 123 | 8. Enter `heroku logs --tail` in the Terminal and find the location of "My IP". Copy the IP address. 124 | For example: 125 | ``` 126 | 2023-03-05T13:38:36.171417+00:00 app[web.1]: My IP: 54.78.178.135 127 | ``` 128 | 9. Go back to [Binance](https://www.binance.com/en), click `Edit restrictions ` for the Token you just created -> check `Restrict access to trusted IPs only (Recommended)` under `IP access restrictions` -> add the IP from the previous step.  129 | 10. Check the box for `Enable Futures` at the top. 130 | 11. Click `Save` 131 | 3. CronJob Scheduled Request Sending 132 | 1. Register/Login to [cron-job.org](https://cron-job.org/en/) 133 | 2. Choose `CREATE CRONJOB` in the right upper corner of the backend 134 | 3. Enter `ChatGPT-Trading-Bot` in `Title`, and enter the URL from the previous step. 135 | 4. Below, send every `5 minutes` 136 | 5. Click `CREATE` 137 | 4. Trading View Alert Configuration 138 | 1. In TradingView's `Strategy Tester`, select your strategy, and click on the bell icon 139 | 2. In `Settings`, enter the message below: 140 | ```json 141 | { 142 | "passphrase": "PASSPHRASE used during setup", 143 | "symbol": "Cryptocurrency to trade", 144 | "leverage": Leverage amount, 145 | "quantity": Quantity to trade, 146 | "time": "{{time}}", 147 | "close": {{close}}, 148 | "message": {{strategy.order.alert_message}} 149 | } 150 | ``` 151 | For example: 152 | ```json 153 | { 154 | "passphrase": "Zw'4Tx^5/]f/pN>}fx*9m6 Explanation: Contract trading set `BTCUSDT` trading pair leverage to `10` times, quantity `0.002` BTC. 164 | 3. Notifications Configuration 165 | 1. Webhook URL setting: The URL in Heroku (`Settings` -> `Domains`) + `/webhook` 166 | - Example 167 | ``` 168 | https://chatgpt-trading-bot.herokuapp.com/webhook 169 | ``` 170 | 171 | ## Support Us 172 | Like this free project? Please consider [supporting us](https://www.buymeacoffee.com/explainthis) to keep it running. 173 | 174 | [Buy Me A Coffee](https://www.buymeacoffee.com/explainthis) 175 | 176 | ## License 177 | [MIT](LICENSE) 178 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ChatGPT Trading Bot 2 | 3 | 中文 | [English](README.en.md) 4 | 5 | [![license](https://img.shields.io/pypi/l/ansicolortags.svg)](LICENSE) [![Release](https://img.shields.io/github/v/release/TheExplainthis/ChatGPT-Trading-Bot)](https://github.com/TheExplainthis/ChatGPT-Trading-Bot/releases/) 6 | 7 | 8 | ![Demo](https://github.com/TheExplainthis/ChatGPT-Trading-Bot/blob/main/demo/demo0.png) 9 | 10 | 這個 Repository 會教你如何叫 ChatGPT 幫你寫交易程式,並且將程式碼部署到 Heroku 上,實現自動化交易。本篇所串接的交易所為幣安交易所,若玩家們有其他交易平台,可以自行串接。 11 | 12 | ## ChatGPT 訓練方式 13 | 1. 首先,我先讓 NotionAI 幫我發想了十個可能的交易策略,如下: 14 | - A momentum trading strategy based on price and volume data 15 | - A mean reversion strategy using Bollinger Bands and RSI indicators 16 | - A trend following strategy using moving averages and MACD indicator 17 | - A breakout trading strategy based on support and resistance levels 18 | - A pairs trading strategy using cointegration analysis 19 | - A news-based trading strategy using sentiment analysis on financial news 20 | - An arbitrage trading strategy using cross-market analysis 21 | - A swing trading strategy using candlestick patterns and chart analysis 22 | - A quantitative trading strategy based on statistical models and machine learning algorithms 23 | - A position trading strategy using fundamental analysis and value investing principles 24 | 2. 跟 ChatGPT 這樣說:`Give me pipescript code with version 4 running on TradingView for {交易策略}` ,所以隨便一個範例如下: 25 | ``` 26 | Give me pipescript code with version 4 running on TradingView for A momentum trading strategy based on price and volume data. 27 | ``` 28 | 3. 複製 ChatGPT 的程式碼,有些部分需要微調 29 | - 針對程式碼的第二行,有時候 ChatGPT 會給你 `study` 要改成 `strategy` , 30 | - 有時候進出場的那段程式碼,他會給你 31 | ```python 32 | if buy_signal 33 | alert("Buy Signal") 34 | if sell_signal 35 | alert("Sell Signal") 36 | ``` 37 | - 要改成以下的程式碼,才會在回測時觸發 38 | ```python 39 | if buy_signal 40 | strategy.entry("Buy", strategy.long) 41 | if sell_signal 42 | strategy.entry("Sell", strategy.short) 43 | ``` 44 | - 在 Buy, Sell, Buy Exit, Sell Exit 後面,需要添加參數 `alert_message`,這樣後續設定 Notification 時才不會出錯。 45 | ```python 46 | if long_bb and long_ma and macd_above_signal and time >= start_time 47 | strategy.entry("Buy", strategy.long, alert_message="Buy") 48 | if short_bb and short_ma and macd_below_signal and time >= start_time 49 | strategy.entry("Sell", strategy.short, alert_message="Sell") 50 | 51 | if exit_bb or exit_ma 52 | strategy.exit('Buy Exit', 'Buy', alert_message="Buy_Exit") 53 | strategy.exit('Sell Exit', 'Sell', alert_message="Sell_Exit") 54 | ``` 55 | > 注意:有時候 ChatGPT 給你的程式碼會跑不動,因此可以多問他幾次,或者將錯誤訊息拋給他。 56 | 4. 調整參數,以獲得最好的成效,如下圖所示: 57 | 58 | ![Demo](https://github.com/TheExplainthis/ChatGPT-Trading-Bot/blob/main/demo/demo1.png) 59 | 60 | 61 | ## 自動化流程安裝步驟 62 | ### Token 取得 63 | 1. 登入 [Binance](https://www.binance.com/en) 64 | 2. 登入後左方有一個 `API Management` ,進入後再右上角按下 `Create` 65 | 3. 就會取得 `API Key` 和 `Secret Key` 66 | 67 | ### 專案設置 68 | 1. Fork Github 專案: 69 | 1. 註冊/登入 [GitHub](https://github.com/) 70 | 2. 進入 [ChatGPT-Trading-Bot](https://github.com/TheExplainthis/ChatGPT-Trading-Bot) 71 | 3. 點選 `Star` 支持開發者 72 | 4. 點選 `Fork` 複製全部的程式碼到自己的倉庫 73 | 2. 部署空間註冊(免費空間): 74 | 1. 註冊/登入 [Heroku](https://www.heroku.com/) 75 | 2. 右上方有一個 `New` -> `Create new app` 76 | 3. App Name: `輸入此 App 名稱` , `Region`: `Europe` 77 | 4. `Create app` 78 | > 注意:選擇部署平台時有兩個限制:幣安若需要合約交易,則需要有 IP 位置、幣安的 API 有地區限制,像是 IP 在美國的地區就無法使用。 79 | 80 | ### 專案執行 81 | 1. 環境變數設定 82 | 1. 點擊 `Settings` -> `Reveal Config Vars` 83 | 2. 新增環境變數,需新增: 84 | 1. API Key: 85 | - key: `API_KEY` 86 | - value: `[由上方步驟一取得]` 87 | 2. API SECRET KEY: 88 | - key: `API_SECRET_KEY` 89 | - value: `[由上方步驟一取得]` 90 | 3. PASSPHRASE -> 用途是 TradingView 打 Request 到 Server 的時候,可以當作 Token 的東西,避免讓所有人都可以打 API 91 | - key: `PASSPHRASE` 92 | - value: `用戶自行生成,步驟四會再用到` 93 | 2. 部署步驟 94 | 1. 利用 Terminal 進入 `ChatGPT-Trading-Bot` 所在的資料夾 95 | 2. `ls` 看一下資料夾,是否和以下相同 96 | ``` 97 | Procfile 98 | demo 99 | src 100 | main.py 101 | runtime.txt 102 | README.md 103 | README.en.md 104 | requirements.txt 105 | ``` 106 | 3. 安裝 [Heroku cli](https://devcenter.heroku.com/articles/heroku-cli#install-the-heroku-cli) 107 | 4. 部署,可參考 Deploy 頁面下方流程 108 | - 先登入 Heroku,在 Terminal 輸入: 109 | ``` 110 | $ heroku login 111 | ``` 112 | - 新增位置,在 Terminal 輸入: 113 | ``` 114 | $ heroku git:remote -a [你的 App Name] 115 | ``` 116 | 5. 將 repo 推上 Heroku,在 Terminal 輸入: 117 | ``` 118 | $ git push heroku main 119 | ``` 120 | 6. 部署成功後,你的網址列會在 `Settings` -> `Domains` 121 | 7. 按下連結後,會看到 `Hello, World!` 122 | 8. Terminal 輸入 `heroku logs --tail` 找到 "My IP" 的地方,把 IP 複製下來。例如: 123 | ``` 124 | 2023-03-05T13:38:36.171417+00:00 app[web.1]: My IP: 54.78.178.135 125 | ``` 126 | 9. 回到 [Binance](https://www.binance.com/en) ,剛剛那個 Token ,點擊 `Edit restrictions` -> 下方 `IP access restrictions` 勾選 `Restrict access to trusted IPs only (Recommended)` -> 並將上一步驟 IP 加進去。 127 | 10. 上方 `Enable Futures` 打勾 128 | 11. 按下 `Save` 129 | 3. CronJob 定時發送請求 130 | 1. 註冊/登入 [cron-job.org](https://cron-job.org/en/) 131 | 2. 進入後面板右上方選擇 `CREATE CRONJOB` 132 | 3. `Title` 輸入 `ChatGPT-Trading-Bot`,網址輸入上一步驟的網址 133 | 4. 下方則每 `5 分鐘` 打一次 134 | 5. 按下 `CREATE` 135 | 4. Trading View Alert 設定 136 | 1. 在 TradingView 下方 `Strategy Tester` ,選擇你的策略,並按下鬧鐘的 icon 137 | 2. `Settings` 下方 Message 輸入: 138 | ```json 139 | { 140 | "passphrase": "環境設定時的 PASSPHRASE", 141 | "symbol": "要交易的幣種", 142 | "leverage": 槓桿數, 143 | "quantity": 要交易的數量, 144 | "time": "{{time}}", 145 | "close": {{close}}, 146 | "message": {{strategy.order.alert_message}} 147 | } 148 | ``` 149 | 例如 150 | ```json 151 | { 152 | "passphrase": "Zw'4Tx^5/]f/pN>}fx*9m6 解釋:合約交易設定 `BTCUSDT` 交易對槓桿為 `10` 倍,數量為 `0.002` 個比特幣。 162 | 3. Notifications 設定 163 | 1. Webhook URL 設定: Heroku 裡的 URL (`Settings` -> `Domains` )+ `/webhook` 164 | - 例如 165 | ``` 166 | https://chatgpt-trading-bot.herokuapp.com/webhook 167 | ``` 168 | 169 | ## 支持我們 170 | 如果你喜歡這個專案,願意[支持我們](https://www.buymeacoffee.com/explainthis),可以請我們喝一杯咖啡,這會成為我們繼續前進的動力! 171 | 172 | [Buy Me A Coffee](https://www.buymeacoffee.com/explainthis) 173 | 174 | ## 授權 175 | [MIT](LICENSE) 176 | -------------------------------------------------------------------------------- /demo/demo0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheExplainthis/ChatGPT-Trading-Bot/0ea19a841af93da004d882a7c733d66557dc59b7/demo/demo0.png -------------------------------------------------------------------------------- /demo/demo1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheExplainthis/ChatGPT-Trading-Bot/0ea19a841af93da004d882a7c733d66557dc59b7/demo/demo1.png -------------------------------------------------------------------------------- /demo/demo2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheExplainthis/ChatGPT-Trading-Bot/0ea19a841af93da004d882a7c733d66557dc59b7/demo/demo2.png -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request 2 | import requests 3 | 4 | import json 5 | import os 6 | from src.trading import BinanceTrading 7 | from src.logger import logger 8 | 9 | app = Flask(__name__) 10 | 11 | binance_trading = BinanceTrading(os.environ.get('API_KEY'), os.environ.get('API_SECRET_KEY')) 12 | 13 | 14 | @app.route('/webhook', methods=['POST']) 15 | def tradingview_request(): 16 | data = json.loads(request.data) 17 | logger.info(data) 18 | if data.get('passphrase', None) != os.environ.get('PASSPHRASE'): 19 | logger.warning('Wrong passphrase') 20 | return { 21 | 'code': 'error', 22 | 'message': 'Invalid passphrase' 23 | } 24 | 25 | symbol = data.get('symbol') 26 | leverage = data.get('leverage') 27 | quantity = data.get('quantity') 28 | max_quantity_ratio = data.get('max_quantity_ratio') 29 | logger.info(f'symbol:{symbol} ,leverage: {leverage}, quantity: {quantity}, max_quantity_ratio: {max_quantity_ratio}, message: {data.get("message")}') 30 | if data.get('message') == 'Sell' or data.get('message') == 'Buy_Exit': 31 | logger.info(f'SELL: {symbol}, leverage: {leverage}, quantity: {quantity}, max_quantity_ratio: {max_quantity_ratio}') 32 | binance_trading.sell(symbol, leverage, quantity, max_quantity_ratio) 33 | elif data.get('message') == 'Buy' or data.get('message') == 'Sell_Exit': 34 | logger.info(f'BUY: {symbol}, leverage: {leverage}, quantity: {quantity}, max_quantity_ratio: {max_quantity_ratio}') 35 | binance_trading.buy(symbol, leverage, quantity, max_quantity_ratio) 36 | return {"message": "successful"} 37 | 38 | 39 | @app.route('/', methods=['GET']) 40 | def home(): 41 | return 'Hello, World!' 42 | 43 | 44 | if __name__ == "__main__": 45 | print(f"My IP: {requests.get('https://api.my-ip.io/ip').text}") 46 | app.run(host='0.0.0.0', port=int(os.environ.get('PORT'))) 47 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | python-binance==1.0.15 2 | Flask==2.2.3 -------------------------------------------------------------------------------- /runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.9.16 -------------------------------------------------------------------------------- /src/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheExplainthis/ChatGPT-Trading-Bot/0ea19a841af93da004d882a7c733d66557dc59b7/src/__init__.py -------------------------------------------------------------------------------- /src/logger.py: -------------------------------------------------------------------------------- 1 | import os 2 | import logging 3 | import logging.handlers 4 | 5 | 6 | class CustomFormatter(logging.Formatter): 7 | __LEVEL_COLORS = [ 8 | (logging.DEBUG, '\x1b[40;1m'), 9 | (logging.INFO, '\x1b[34;1m'), 10 | (logging.WARNING, '\x1b[33;1m'), 11 | (logging.ERROR, '\x1b[31m'), 12 | (logging.CRITICAL, '\x1b[41m'), 13 | ] 14 | __FORMATS = None 15 | 16 | @classmethod 17 | def get_formats(cls): 18 | if cls.__FORMATS is None: 19 | cls.__FORMATS = { 20 | level: logging.Formatter( 21 | f'\x1b[30;1m%(asctime)s\x1b[0m {color}%(levelname)-8s\x1b[0m \x1b[35m%(name)s\x1b[0m -> %(message)s', 22 | '%Y-%m-%d %H:%M:%S' 23 | ) 24 | for level, color in cls.__LEVEL_COLORS 25 | } 26 | return cls.__FORMATS 27 | 28 | def format(self, record): 29 | formatter = self.get_formats().get(record.levelno) 30 | if formatter is None: 31 | formatter = self.get_formats()[logging.DEBUG] 32 | if record.exc_info: 33 | text = formatter.formatException(record.exc_info) 34 | record.exc_text = f'\x1b[31m{text}\x1b[0m' 35 | 36 | output = formatter.format(record) 37 | record.exc_text = None 38 | return output 39 | 40 | 41 | class LoggerFactory: 42 | @staticmethod 43 | def create_logger(formatter, handlers): 44 | logger = logging.getLogger('chatgpt_logger') 45 | logger.setLevel(logging.INFO) 46 | for handler in handlers: 47 | handler.setLevel(logging.DEBUG) 48 | handler.setFormatter(formatter) 49 | logger.addHandler(handler) 50 | return logger 51 | 52 | 53 | class FileHandler(logging.FileHandler): 54 | def __init__(self, log_file): 55 | os.makedirs(os.path.dirname(log_file), exist_ok=True) 56 | super().__init__(log_file) 57 | 58 | 59 | class ConsoleHandler(logging.StreamHandler): 60 | pass 61 | 62 | 63 | formatter = CustomFormatter() 64 | console_handler = ConsoleHandler() 65 | logger = LoggerFactory.create_logger(formatter, [console_handler]) -------------------------------------------------------------------------------- /src/trading.py: -------------------------------------------------------------------------------- 1 | from binance import Client 2 | 3 | 4 | class BinanceLeverage: 5 | def __init__(self, api_key, api_secret): 6 | self.client = Client(api_key, api_secret) 7 | self.leverage_mapping = {} 8 | 9 | def change_leverage(self, symbol, leverage): 10 | self.leverage_mapping[symbol] = leverage 11 | self.client.futures_change_leverage(symbol=symbol, leverage=leverage) 12 | 13 | 14 | class BinanceBalance: 15 | def __init__(self, api_key, api_secret): 16 | self.client = Client(api_key, api_secret) 17 | 18 | def get_max_qty(self, symbol, leverage): 19 | account_balance = self.client.futures_account_balance() 20 | ticker_price = self.client.futures_symbol_ticker(symbol=symbol) 21 | mark_price = float(ticker_price['price']) 22 | for asset in account_balance: 23 | if asset['asset'] == symbol[-4:]: 24 | balance = float(asset['balance']) 25 | return balance * leverage / mark_price 26 | 27 | 28 | class BinanceOrder: 29 | def __init__(self, api_key, api_secret): 30 | self.client = Client(api_key, api_secret) 31 | self.leverage = BinanceLeverage(api_key, api_secret) 32 | self.balance = BinanceBalance(api_key, api_secret) 33 | 34 | def get_precision(self, symbol): 35 | info = self.client.futures_exchange_info() 36 | for x in info['symbols']: 37 | if x['symbol'] == symbol: 38 | return x['quantityPrecision'] 39 | 40 | def create_order(self, side, symbol, leverage, quantity=None, max_quantity_ratio=0.1): 41 | self.leverage.change_leverage(symbol, leverage) 42 | if not quantity: 43 | quantity = self.balance.get_max_qty(symbol, leverage) * max_quantity_ratio 44 | precision = self.get_precision(symbol) 45 | quantity = float(round(quantity, precision)) 46 | self.client.futures_create_order( 47 | symbol=symbol, 48 | type='MARKET', 49 | side=side, 50 | quantity=quantity 51 | ) 52 | 53 | 54 | class BinanceTrading: 55 | def __init__(self, api_key, api_secret): 56 | self.order = BinanceOrder(api_key, api_secret) 57 | 58 | def buy(self, symbol, leverage, quantity=None, max_quantity_ratio=0.1): 59 | self.order.create_order(Client.SIDE_BUY, symbol, leverage, quantity, max_quantity_ratio) 60 | 61 | def sell(self, symbol, leverage, quantity=None, max_quantity_ratio=0.1): 62 | self.order.create_order(Client.SIDE_SELL, symbol, leverage, quantity, max_quantity_ratio) --------------------------------------------------------------------------------