ChatGPT 自動化交易教學文,協助你實現自動化投資理財!(實測有效)

2023年3月6日

🚀 ChatGPT 求職工作術
想透過 ChatGPT 提升求職與工作效率嗎?《ChatGPT 高效求職與工作術》限時 46 折優惠中👉 前往上課

💡 溫馨小提醒:大家都知道 ChatGPT 很會瞎掰和裝懂,所以要拿你的真金白銀跟他玩,可能需要評估一下,本文僅當作學術研究、飯後閒聊話題。

成效表現

ChatGPT Trading Bot Demo 1
ChatGPT Trading Bot Demo 1
ChatGPT Trading Bot Demo 2
ChatGPT Trading Bot Demo 2

快速看一下我叫 ChatGPT 幫我寫的策略成效,以上兩個是完全不同的策略,而微調一下參數後,在比特幣的交易上都有不錯的成效,而這是怎麼做到的呢?我們一步一步來拆解。

本次專案程式碼:TheExplainthis/ChatGPT-Trading-Bot,如果你在實作上遇到任何問題,歡迎直接在 Github 上發一個 issue,我們會定期回答 issue 專區的問題。

ChatGPT 訓練方式

  1. 首先,我先讓 Notion AI 幫我發想了十個可能的交易策略,如下:

    • A momentum trading strategy based on price and volume data
    • A mean reversion strategy using Bollinger Bands and RSI indicators
    • A trend following strategy using moving averages and MACD indicator
    • A breakout trading strategy based on support and resistance levels
    • A pairs trading strategy using cointegration analysis
    • A news-based trading strategy using sentiment analysis on financial news
    • An arbitrage trading strategy using cross-market analysis
    • A swing trading strategy using candlestick patterns and chart analysis
    • A quantitative trading strategy based on statistical models and machine learning algorithms
    • A position trading strategy using fundamental analysis and value investing principles
  2. 再來,可以跟 ChatGPT 說 Give me pipescript code with version 4 running on TradingView for {交易策略} ,所以隨便一個範例如下:

    Give me pipescript code with version 4 running on TradingView for A momentum trading strategy based on price and volume data.
    
  3. 複製 ChatGPT 的程式碼,有些部分需要微調,如下:

    • 對程式碼的第二行,有時候 ChatGPT 會給你 study 要改成 strategy

    • 買進賣出信號調整:

      • 有時候進出場的那段程式碼,他會給你
        if buy_signal
        	alert("Buy Signal")
        if sell_signal
        	alert("Sell Signal")
        
      • 要改成以下的程式碼,才會在回測時觸發
        if buy_signal
        	strategy.entry("Buy", strategy.long)
        if sell_signal
        	strategy.entry("Sell", strategy.short)
        
    • 在 Buy, Sell, Buy Exit, Sell Exit 後面,需要添加參數 alert_message,這樣後續設定 Notification 時才不會出錯。

      if long_bb and long_ma and macd_above_signal and time >= start_time
      strategy.entry("Buy", strategy.long, alert_message="Buy")
      if short_bb and short_ma and macd_below_signal and time >= start_time
      strategy.entry("Sell", strategy.short, alert_message="Sell")
      
      if exit_bb or exit_ma
          strategy.exit('Buy Exit', 'Buy', alert_message="Buy_Exit")
          strategy.exit('Sell Exit', 'Sell', alert_message="Sell_Exit")
      

      ⚠️ 有時候 ChatGPT 給你的程式碼會跑不動,因此可以多問他幾次,或者將錯誤訊息拋給他。

  4. 調整參數,以獲得最好的成效,如下圖所示:

    ChatGPT Trading Bot Demo 1
    ChatGPT Trading Bot Demo 1

自動化流程安裝步驟

Token 取得

  1. 登入 Binance

  2. 登入後左方有一個 API Management ,進入後再右上角按下 Create

    Binance Create Token 1
    Binance Create Token 1
    Binance Create Token 2
    Binance Create Token 2
  3. 就會取得 API KeySecret Key

    Binance Create Token 3
    Binance Create Token 3

專案設置

  1. Fork Github 專案:

    1. 註冊/登入 GitHub
    2. 進入 ChatGPT-Trading-Bot
    3. 點選 Star 支持開發者
    4. 點選 Fork 複製全部的程式碼到自己的倉庫
  2. 部署空間註冊(免費空間):

    1. 註冊/登入 Heroku

    2. 右上方有一個 New -> Create new app

    3. App Name: 輸入此 App 名稱 , Region: Europe

    4. 按下Create app

      Heroku Create app
      Heroku Create app

    ⚠️ 選擇部署平台時有兩個限制:幣安若需要合約交易,則需要有 IP 位置、幣安的 API 有地區限制,像是 IP 在美國的地區就無法使用。

專案執行

  1. 環境變數設定

    1. 點擊 Settings -> Reveal Config Vars
    2. 新增環境變數,需新增:
      • API Key: key: API_KEY value: [由上方步驟一取得]
      • API SECRET KEY: key: API_SECRET_KEY value: [由上方步驟一取得]
      • PASSPHRASE -> 用途是 TradingView 打 Request 到 Server 的時候,可以當作 Token 的東西,避免讓所有人都可以打 API key: PASSPHRASE value: 用戶自行生成,步驟四會再用到
    Heroku Add Environment Variables
    Heroku Add Environment Variables
  2. 部署步驟

    1. 利用 Terminal 進入 ChatGPT-Trading-Bot 所在的資料夾 2. ls 看一下資料夾,是否和以下相同

    Procfile; demo; src; main.py; runtime.txt; README.md; README.en.md; requirements.txt;

    Heroku Add Environment Variables
    Heroku Add Environment Variables

    3. 安裝 Heroku cli 4. 部署,可參考 Deploy 頁面下方流程 - 先登入 Heroku,在 Terminal 輸入: jsx $ heroku login

    Heroku Add Environment Variables
    Heroku Add Environment Variables

    按下 Enter 後,他會打開瀏覽器,並且要求登入,登入成功後即完成。 - 新增位置,在 Terminal 輸入: jsx $ heroku git:remote -a [你的 App Name] 5. 將 repo 推上 Heroku,在 Terminal 輸入:

    jsx $ git push heroku main

    6. 部署成功後,你的網址列會在 Settings -> Domains

    Heroku Get URL
    Heroku Get URL

    7. 按下連結後,會看到 Hello, World! 8. Terminal 輸入 heroku logs --tail 找到 "My IP" 的地方,把 IP 複製下來。例如:

    jsx 2023-03-05T13:38:36.171417+00:00 app[web.1]: My IP: 54.78.178.135

    Heroku Get IP
    Heroku Get IP

    9. 回到 Binance ,剛剛那個 Token ,點擊 Edit restrictions -> 下方 IP access restrictions 勾選 Restrict access to trusted IPs only (Recommended) -> 並將上一步驟 IP 加進去。 10. 上方 Enable Futures 打勾 11. 按下 Save

    Heroku Get IP
    Heroku Get IP

⚠️ 免費版本的 Heroku 若 30 分鐘內無人發送請求,則系統會進入休眠,因此需要下一步驟。

  1. CronJob 定時發送請求

    1. 註冊/登入  cron-job.org

    2. 進入後面板右上方選擇  CREATE CRONJOB

      CronJob Step 1
      CronJob Step 1
    3. Title  輸入  ChatGPT-Trading-Bot,網址輸入上一步驟的網址

    4. 下方則每  5 分鐘  打一次

    5. 按下  CREATE

      CronJob Step 2
      CronJob Step 2
  2. Trading View Alert 設定

    1. 在 TradingView 下方 Strategy Tester ,選擇你的策略,並按下鬧鐘的 icon

    2. Settings 下方 Message 格式如下:

      { "passphrase": "環境設定時的 PASSPHRASE", "symbol": "要交易的幣種", "leverage": 槓桿數, "quantity": 要交易的數量, "time": "{{time}}", "close": {{close}}, "message": {{strategy.order.alert_message}} }

      例如:

      { "passphrase": "Zw'4Tx^5/]f/pN>}fx*9m6<X,fxLx;x(", "symbol": "BTCUSDT", "leverage": 10, "quantity": 0.002, "time": "{{time}}", "close": {{close}}, "message": {{strategy.order.alert_message}} }

    👉 解釋:合約交易設定 BTCUSDT 交易對槓桿為 10 倍,數量為 0.002 個比特幣。

  3. Notifications 設定

    1. Webhook URL 設定: Heroku 裡的 URL (Settings -> Domains )+ /webhook

    例如:

    https://chatgpt-trading-bot.herokuapp.com/webhook

    Notifications setting
    Notifications setting

Q&A

  1. 如何測試自動化串接是否有串上?

    可以在 TradingView 上,開一個即時的 Alert,像是當前幣價為 25000,則設一個 Alert 為 cross 25000,然後讓他快速觸發,但因為是即時觸發,而非策略觸發,所以 "message": {{strategy.order.alert_message}} 可以改成 "message": "Buy" ,不然 message 會是空的。

  2. 每一次交易一定要設定 quantity 不能是一個比例嗎?

    這邊我多設定一個參數是 max_quantity_ratio ,他會根據槓桿數,計算最大的 quantity 數量,再乘以一個比例,舉例來說 max_quantity_ratio 設為 0.01 則表示 1% 的資產。

  3. 程式碼有誤,該如何 Debug?

    可以在 Terminal 輸入 heroku logs --tail,先確認錯誤問題為何,若無法自行解決可以發 Issue

🧵 如果你想收到最即時的內容更新,可以在 FacebookInstagram 上追蹤我們