# Python 自動下單：FinLab order\_api 串 GCP 部署台股策略

台股研究 2022年8月31日 約 7 分鐘閱讀

Python 自動下單的順序應先用 finlab 回測產出目標部位，再用 FinLab order\_api 的 Position 與 OrderExecutor 串接券商 API。本文示範把台股選股策略部署到 GCP Cloud Function，搭配 Cloud Scheduler 定期執行，並提醒先用 view\_only 預覽、保護觸發網址與憑證。

回測通過後再接券商 API 自動下單

## Python 自動下單先分三層：回測、目標部位、券商送單

如果你搜尋「Python 自動下單」、「股票自動交易程式」或「自動交易系統」，真正要解的是三件事：策略能不能被回測驗證、回測結果能不能轉成目標部位、目標部位能不能安全送到券商。這篇示範的是最後一段：把 FinLab 回測產生的 `report` 轉成 `Position`，再用 `OrderExecutor` 串接券商 API，部署到 GCP Cloud Function 定期執行。

| 層級    | 這一層要確認                  | 本文用到的工具                                                                                                     |
| ----- | ----------------------- | ----------------------------------------------------------------------------------------------------------- |
| 研究與回測 | 策略是否有明確規則、是否扣交易成本、是否能重跑 | [FinLab 回測工具](https://finlab.finance/tools/backtesting)、`finlab.backtest.sim()`                             |
| 目標部位  | 回測結果如何換成每檔股票該買賣多少股      | `Position.from_report(report, fund)`                                                                        |
| 自動下單  | 下單前先預覽委託，確認後才送到券商       | [FinLab order\_api](https://doc.finlab.tw/details/order_api/)、`OrderExecutor.create_orders(view_only=True)` |
| 雲端排程  | 固定時間啟動，但不外洩觸發網址與憑證      | GCP Cloud Function、Cloud Scheduler、Cloud Storage                                                            |

下單前請先讀 [程式交易是什麼](https://finlab.finance/tools/program-trading)，釐清「回測」與「自動下單」的差別；如果策略還沒成形，先用 [台股股票選股器](https://finlab.finance/tools/stock-screener) 或 [股票選股教學](https://finlab.finance/tools/stock-selection) 找出可測的條件，再回到本文處理部署。

## 前情提要

在自動交易的[上集](https://finlab.finance/blog/finlab-gcp-auto-trading-part1)中，我們完成了永豐和 FinLab 相關的前置作業，包括申請交易憑證、打包策略程式碼、加入下單模組。

在本篇文章中，我們會將這些東西上傳到 GCP 以完成 Cloud Function 部署，最後用 Cloud Scheduler 定期呼叫 Cloud Function，讓策略能固定時間計算目標部位並送出委託。

## 流程圖

附上流程圖幫大家複習一下，如果沒有看過[上集](https://finlab.finance/blog/finlab-gcp-auto-trading-part1)的同學，記得先回去補課喔！

[![自動交易設定流程圖](https://r2.finlab.finance/blog/auto-trading-part2/Untitled-1-1024x594.png)](https://r2.finlab.finance/blog/auto-trading-part2/Untitled-1-1024x594.png)

依本文重跑

## 執行這個策略

複製提示詞，讓 AI 依照上方證據的資料、條件與風險檢查重跑一次。

告訴你的AI：

幫我用 FinLab 建立一個台股自動下單前檢查清單：先回測策略、產生目標部位、用 view\_only 預覽訂單，再整理部署到 GCP 前要保護的環境變數與觸發網址，請讀：https\://finlab.finance/setup?relatedUrl=/blog/python-auto-trading-gcp-cloud-function

[免安裝，開啟 FinLab Studio](https://studio.finlab.finance/chat?lang=zh\&research_context=%7B%22v%22%3A1%2C%22source_url%22%3A%22https%3A%2F%2Ffinlab.finance%2Fblog%2Fpython-auto-trading-gcp-cloud-function%22%2C%22task%22%3A%22%E5%B9%AB%E6%88%91%E7%94%A8+FinLab+%E5%BB%BA%E7%AB%8B%E4%B8%80%E5%80%8B%E5%8F%B0%E8%82%A1%E8%87%AA%E5%8B%95%E4%B8%8B%E5%96%AE%E5%89%8D%E6%AA%A2%E6%9F%A5%E6%B8%85%E5%96%AE%EF%BC%9A%E5%85%88%E5%9B%9E%E6%B8%AC%E7%AD%96%E7%95%A5%E3%80%81%E7%94%A2%E7%94%9F%E7%9B%AE%E6%A8%99%E9%83%A8%E4%BD%8D%E3%80%81%E7%94%A8+view_only+%E9%A0%90%E8%A6%BD%E8%A8%82%E5%96%AE%EF%BC%8C%E5%86%8D%E6%95%B4%E7%90%86%E9%83%A8%E7%BD%B2%E5%88%B0+GCP+%E5%89%8D%E8%A6%81%E4%BF%9D%E8%AD%B7%E7%9A%84%E7%92%B0%E5%A2%83%E8%AE%8A%E6%95%B8%E8%88%87%E8%A7%B8%E7%99%BC%E7%B6%B2%E5%9D%80%22%7D)

## 免責聲明

FinLab於此文章中所提供的程式碼僅供參考，會隨著套件版本更動、硬體設備之故障、失效或人為上之疏失導致，導致下單狀況不如交易者之預期。使用者在使用此文章之程式碼前，務必自行審慎評估，並自負投資風險及盈虧。如使用FinLab所提供之程式碼致生損失，本公司不負擔任何賠償及法律責任。

## Google Cloud Platform (GCP)

Google Cloud Platform是Google的雲端平台，有著一系列由Google提供的雲端運算服務。

我們這次會使用到其中三個雲端服務：

* Cloud Storage：雲端的儲存空間，用來存放永豐的交易憑證
* Cloud Function：雲端執行FinLab[選股策略](https://finlab.finance/tools/stock-selection)和下單程式碼。
* Cloud Sceduler：雲端排程工具，定期執行部署的Cloud Function。

### GCP 要收費嗎？

新用戶前三個月會贈送300美元的抵免額，對佈署自動交易程式來說足夠了。三個月過後，當你確認要付費繼續使用時，才會開始扣款。

依照目前 Cloud Function 的定價，試用期過後，每個月大約是1元台幣，詳細計算方式如下：

* 不論是否是試用期，Cloud Function 呼叫200萬次以內，都是免費的。即便每天執行10次，一個月也才300次，並不會達到收費門檻。
* 在文章中，會看到用 https 也就是網頁的方式，來呼叫 cloud function，這個部分，假如是 5GB 以內，也會是免費的，假設所產生的網頁以 500kb 來計算，每月要執行 200 萬次才會達到門檻。
* 由於我們上傳 google cloud function，會有存放系統的成本，所以每個月會酌收0.026美金，大約是 1 元台幣。

有疑問的同學可以到 [Google cloud function 的定價](https://cloud.google.com/functions/pricing)來查看更詳細的定價，接下來就讓我們開始吧！

### 註冊帳號

首先到GCP的[官網](https://cloud.google.com/landing/free-trial?hl=zh-tw\&utm_source=google\&utm_medium=cpc\&utm_campaign=japac-TW-all-zh-dr-bkws-all-all-trial-e-dr-1009882\&utm_content=text-ad-none-none-DEV_c-CRE_540744604695-ADGP_Hybrid%20%7C%20BKWS%20-%20EXA%20%7C%20Txt%20~%20GCP%20~%20General_cloud%20-%20platform-KWID_43700061092164566-kwd-87853815\&userloc_1012818-network_g\&utm_term=KW_gcp\&gclid=CjwKCAjwx7GYBhB7EiwA0d8oezDlAskppfC9tDF2fuA7B7Pnms9567QnsT4wjeSyyJLr1Z6SrE14vxoCHroQAvD_BwE\&gclsrc=aw.ds)註冊一個帳號，註冊表單按照自己的狀況填即可。

辦好帳號後進入控制台，就可以在左邊找到Cloud Function 跟 Cloud Storage，建議把他們釘選到最上方，這樣在之後的使用會比較方便。

### 新增專案

大家可以自由地設定專案名稱，但建議專案ID跟專案名稱一致。

[![GCP 新增專案設定畫面](https://r2.finlab.finance/blog/auto-trading-part2/2-1024x355.png)](https://r2.finlab.finance/blog/auto-trading-part2/2-1024x355.png)

[![GCP 建立專案表單畫面](https://r2.finlab.finance/blog/auto-trading-part2/3-1.png)](https://r2.finlab.finance/blog/auto-trading-part2/3-1.png)

這樣就建立好專案囉，接下來請大家進入到新增好的專案中，之後的操作都會在此專案中進行。

### 上傳交易憑證

首先進入Cloud Storage的頁面如下，點選建立。

[![Cloud Storage 建立儲存空間頁面](https://r2.finlab.finance/blog/auto-trading-part2/4.png)](https://r2.finlab.finance/blog/auto-trading-part2/4.png)

值區名稱可以自行設定，我這邊設定為trading\_pass。

[![設定 Cloud Storage 值區名稱為 trading\_pass](https://r2.finlab.finance/blog/auto-trading-part2/5.png)](https://r2.finlab.finance/blog/auto-trading-part2/5.png)

創建好後，進入資料夾中，將先前辦好的交易憑證檔案上傳。

[![將永豐交易憑證上傳至 Cloud Storage 值區](https://r2.finlab.finance/blog/auto-trading-part2/6.png)](https://r2.finlab.finance/blog/auto-trading-part2/6.png)

### 部署 Cloud Function

#### 啟用API

到Cloud Function的頁面，點選建立函式，並按照提示啟用API。

[![建立 Cloud Function 函式並啟用 API](https://r2.finlab.finance/blog/auto-trading-part2/7-1024x535.png)](https://r2.finlab.finance/blog/auto-trading-part2/7-1024x535.png)

#### 基本設定

環境選第一代、函式名稱可自定義、地區選台灣。

[![Cloud Function 基本設定：環境第一代、地區選台灣](https://r2.finlab.finance/blog/auto-trading-part2/8.png)](https://r2.finlab.finance/blog/auto-trading-part2/8.png)

#### 觸發條件設定

[![Cloud Function 觸發條件設定畫面](https://r2.finlab.finance/blog/auto-trading-part2/9.png)](https://r2.finlab.finance/blog/auto-trading-part2/9.png)

#### 記憶體和時間配置設定

記憶體和時間的部分，個人習慣先配置到最大。等確定佈署成功之後，再自行調整縮小到適合的大小。

[![Cloud Function 記憶體和執行時間配置設定](https://r2.finlab.finance/blog/auto-trading-part2/10.png)](https://r2.finlab.finance/blog/auto-trading-part2/10.png)

#### 環境變數設定

環境變數主要放券商登入、憑證路徑與雲端執行需要的授權資訊。FinLab 登入請先依官方文件把授權放在環境變數或已登入快取，程式碼裡不要直接寫 token。

剩餘兩個路徑變數則按照範例輸入即可，是為了因應Cloud Function規定存取和讀取都需要在/tmp目錄下面所做的特別設定。

[![環境變數設置](https://r2.finlab.finance/blog/auto-trading-part2/image.png)](https://r2.finlab.finance/blog/auto-trading-part2/image.png)

#### 程式碼初始設定

設定完成後進到程式碼頁面，會有一支預設程式碼和package檔。

將檔案全部刪掉，並把執行階段改為**自己的Python版本**，進入點改為main，並新增五個空的檔案，檔名如下圖。

[![Cloud Function 程式碼編輯頁面與新增的五個檔案](https://r2.finlab.finance/blog/auto-trading-part2/12-1024x625.png)](https://r2.finlab.finance/blog/auto-trading-part2/12-1024x625.png)

接下來我會對每個檔案說明其作用，並附上程式碼。

#### run\_strategy.py

將我們上面打包好的 function 放進雲端執行。FinLab 登入用 `finlab.login()` 讀取本機或環境變數中的授權狀態，避免在程式碼中留下 token。

顯示程式碼

```
import finlab
import os
from finlab.backtest import sim
from finlab import data
 
finlab.login()
 
def run_strategy(): #將程式碼包裝成function，並回傳report這個物件(下單會用到)
  close = data.get("price:收盤價")
  position = (close == close.rolling(250).max())
  report = sim(position, resample="M", name="創年新高策略",upload=False)
  return report
```

#### make\_order.py

首先請大家先看過[FinLab官方文檔](https://doc.finlab.tw/details/order_api/)，會比較能理解下方的程式碼。

make\_order有兩個輸入變數，一個是sim 所產生的report物件，另一個是這個策略的資金量，也就是你預計要拿多少錢來跑這個策略。

最後make\_order會回傳一個dict物件，key是下單的股票代號、value則是股數，在測試的時候會比較方便確認下單是否正確。

如果不瞭解也沒關係，可以複製程式碼，再更改要投入的資金即可。

顯示程式碼

```
import os
os.chdir("/tmp") #轉到Cloud Function限定的tmp資料夾下面執行
from finlab.online.order_executor import Position
from finlab.online.sinopac_account import SinopacAccount
from finlab.online.order_executor import OrderExecutor
 
def make_order(report,fund=100000): #預設用100,000的資金跑策略
  position = Position.from_report(report, fund)
  acc = SinopacAccount()
  order_executer = OrderExecutor(position , account=acc) 
  # 用模擬模式產生下單的明細並回傳，之後會輸出在網頁上 (optional)
  record = order_executer.create_orders(view_only=True)
  key_list = [f'order{i}:' for i in range(1,len(record)+1)]
  value_list = [{i['stock_id']:i['quantity']} for i in record]
  # 實際下單（會真的下單，初次使用建議收市時測試）
  order_executer.create_orders(market_order=True) #用市價單(要注意滑價，可自行修改)
  return dict(zip(key_list, value_list))
```

#### bucket.py

先前說過，Cloud Function規定資料的讀寫必須在/tmp目錄之下。

connect\_storage的用處是將先前上傳到Cloud Storage的交易憑證，下載至/tmp的目錄下，讓Cloud Function能夠順利讀取，進而登入永豐的交易帳戶。

如果不瞭解可以直接複製程式碼即可。

顯示程式碼

```
from google.cloud import storage
def connect_storage():
  storage_client = storage.Client()
  bucket = storage_client.bucket('trading_pass')
  model_filename = "Sinopac.pfx"
  blob = bucket.blob(model_filename)
  blob.download_to_filename('/tmp/Sinopac.pfx')  
  return
```

#### main.py

main.py裡面的main函式，是Cloud Function執行時的進入點，也就是真正Cloud Function真正執行的函式。

因此我們import了我們上述寫的三份程式碼檔案，在此一一呼叫，先將憑證移到/tmp目錄下，執行FinLab策略，最後執行永豐的下單程式。

顯示程式碼

```
from run_strategy import run_strategy
from make_order import make_order
from bucket import connect_storage
 
def main(request): #request要記得寫，這是Cloud Function 規定的格式
  connect_storage() # 將交易憑證移到/tmp目錄下
  report = run_strategy() #執行FinLab策略，回傳report物件
  record = make_order(report,100000) #用十萬塊下單，回傳下單結果的名細
  return record
```

#### requirements.txt

requirements.txt負責告訴GCP這支Cloud Function需要使用到哪些套件、哪些版本。以下是必定會使用到的套件，版本則可能因人而異，建議選取與本地端相同的版本，避免套件不同版本之間的相容性問題。**若不特別標註版本號，則會自動採用該套件的最新版本。**

大家在撰寫策略時，若有用到其他的套件（ex: pandas），都要記得自己再加上去喔！

顯示程式碼

```
# Function dependencies, for example:
# package==version
# 本篇示範皆使用當前最新版本，讀者可自行指定需固定之版本
finlab
shioaji==0.5.0.dev2 #(2023/2/6編輯)因應永豐API調整，請先暫定此版本
google-cloud-storage
```

如果不知道自己使用的套件版本，可以在jupyter執行以下程式碼。

顯示程式碼

```
# 假設你不知道自己使用的shioaji套件版本
import shioaji
print(shioaji.__version__) #印出套件的版本
# 輸出: 0.3.6.dev2 => 這就是你的shioaji套件版本
```

#### 上傳Cloud Function

一切設定好後，點擊左下角的部署。若部署失敗，可以到logging的頁面，查看error為何，做進一步的修正後，再重新部署即可。

[![Cloud Function 部署成功的畫面](https://r2.finlab.finance/blog/auto-trading-part2/13-1024x161.png)](https://r2.finlab.finance/blog/auto-trading-part2/13-1024x161.png)

#### 權限說明

成功部署Cloud Function後，到權限分頁點選新增，並設定讓所有使用者都可以呼叫此Cloud Function，以便後續Cloud Scheduler的調用。

[![設定 Cloud Function 權限讓所有使用者可呼叫](https://r2.finlab.finance/blog/auto-trading-part2/14.png)](https://r2.finlab.finance/blog/auto-trading-part2/14.png)

#### Cloud Function測試

觸發條件頁面中，**有一個觸發網址，點選它的時候就等同於執行該Cloud Function，也就是下單的動作！**&#x56E0;此**這個網址切記不要外洩**，如果是淘汰或暫時不打算執行的策略，也記得要先下架。

還是會擔心的同學，GCP也有限制使用權限的方法，可以自行Google！

[![Cloud Function 觸發網址設定頁面](https://r2.finlab.finance/blog/auto-trading-part2/15.png)](https://r2.finlab.finance/blog/auto-trading-part2/15.png)

當你點選網址之後，順利的話會出現一個網頁（需要跑一陣子），網頁會顯示下單的明細，方便大家確認下的單是否正確。

備註：用Firefox的瀏覽器來看會比較清楚喔！

譬如以下就是做了三筆交易，分別買進了一張00864B、賣出一張1713、賣出兩張2832。

[![Cloud Function 網頁顯示的下單明細範例](https://r2.finlab.finance/blog/auto-trading-part2/16.png)](https://r2.finlab.finance/blog/auto-trading-part2/16.png)

如果到永豐查看的話會類似下圖，但實際買賣的股票、張數會隨策略和資金的不同而改變，大家只需注意API下的單是否與策略相同即可。

[![永豐帳戶中查看 API 下單結果的畫面](https://r2.finlab.finance/blog/auto-trading-part2/image-6-1024x294.png)](https://r2.finlab.finance/blog/auto-trading-part2/image-6-1024x294.png)

提醒大家在測試的時候，**記得要挑收盤的時候，測試完也要記得把委託單給刪掉**，不然隔天真的成交就麻煩了XD

### 設定 Cloud Scheduler

恭喜大家來到最後一步！搜尋Cloud Scheduler，並點選建立工作。

定義排程的部分，名稱可自行設定，要注意的是執行頻率，像我是習慣開盤前（平日早上8:30）執行我的策略，如果想要自行設定其他時間點執行的話，可以參考這個[網站](https://crontab.guru/)將頻率轉換成Unix-Cron格式。

**備註：建議於晚上7點之後執行，才能獲取最新的資料**

[![Cloud Scheduler 定義排程頻率設定畫面](https://r2.finlab.finance/blog/auto-trading-part2/17.png)](https://r2.finlab.finance/blog/auto-trading-part2/17.png)

設定執行作業時，需填入的網址就是前面Cloud Function的觸發網址。

[![Cloud Scheduler 設定執行作業填入觸發網址](https://r2.finlab.finance/blog/auto-trading-part2/18.png)](https://r2.finlab.finance/blog/auto-trading-part2/18.png)

測試Cloud Scheduler是否正常，點選強制執行，並到永豐帳戶中查看是否有順利下單。

[![Cloud Scheduler 強制執行測試畫面](https://r2.finlab.finance/blog/auto-trading-part2/19-1024x240.png)](https://r2.finlab.finance/blog/auto-trading-part2/19-1024x240.png)

### Colab 版本下單

若在雲端部署上遇到困難，歡迎到[Discord](https://discord.gg/TwNAqsM8uQ)詢問我們，另外我們也提供了[Colab下單腳本](https://colab.research.google.com/drive/1_scpLa_NjuAPaWbKwvSAWfTNCtEIgOVw?usp=sharing)給大家，歡迎大家依照自己的需求選擇！

### 溫馨提醒

**成功部署後，也要定期觀察下單狀況是否如你所預期**，尤其是剛開始使用的時候，以免程式出了BUG，導致賠錢或被追繳的後果。

## 總結

恭喜執行到這裡的大家，已經完成所有的步驟，往後每天GCP都會自動幫大家執行選股策略並且進行下單了！

祝大家一切順利，天天在家睏飽數錢，有任何問題也歡迎在文章下方或到[FinLab粉專](https://www.facebook.com/finlab.python)留言！

這次自動交易的教學就告一段落了。我是阿榤，下次見，掰！(⁎⁍̴̛ᴗ⁍̴̛⁎)

## （2023/4/6 更新） Shioaji Version >= 1.0 環境變數設定

因應永豐更新主要版本至1.0，採用了全新驗證方式。若要使用1.0以後的版本，請先到[永豐官網](https://sinotrade.github.io/tutor/prepare/token/)申請API，將權限設置如下。

[![永豐 Shioaji 1.0 API 權限設置畫面](https://r2.finlab.finance/blog/auto-trading-part2/image-2-1024x448.png)](https://r2.finlab.finance/blog/auto-trading-part2/image-2-1024x448.png)

請將環境變數的設置改為以下

[![Shioaji 1.0版本以後的環境變數設定](https://r2.finlab.finance/blog/auto-trading-part2/image-1.png)](https://r2.finlab.finance/blog/auto-trading-part2/image-1.png)

***

*本文僅供教學與研究參考，不構成投資建議。過去績效不代表未來表現，投資一定有風險，請審慎評估自身風險承受能力。*

![韓承佑](https://finlab.finance/people/cheng-yu-han-avatar.jpg)

韓承佑

創辦人 & 量化研究員

韓承佑是 FinLab 創辦人，也是開源 Python 量化套件 finlab 的作者，長年投入台股與美股的量化策略研究、回測與教學。

[在 GitHub 上追蹤 →](https://github.com/koreal6803) [在 LinkedIn 上連結 →](https://www.linkedin.com/in/cheng-yu-han/)

FinLab AI

### 想建立自己的策略？

用自然語言描述你的選股想法，AI 自動驗證、回測、給你答案

[免費開始](https://finlab.finance/#get-started)

## 更多技術指標研究

[查看全部](https://finlab.finance/blog/category/technical)

* [![美股均值回歸策略回測：買進三日落後的槓桿 ETF，十年年化 51.9%](https://r2.finlab.finance/blog/us-mean-reversion-strategy/chart1_strategy_equity-202610b.png) 美股均值回歸策略回測：買進三日落後的槓桿 ETF，十年年化 51.9% 年化報酬 51.9% · 美股](https://finlab.finance/blog/us-mean-reversion-strategy)
* [![技術分析 vs 基本面分析：台股回測的終極對決](https://r2.finlab.finance/blog/technical-vs-fundamental/chart_validation_2026-10-30.png) 技術分析 vs 基本面分析：台股回測的終極對決 年化報酬 36.3% · 台股](https://finlab.finance/blog/technical-vs-fundamental)
* [![Python 台股 API 比較：FinLab、FinMind、yfinance、證交所 OpenAPI 怎麼選](https://r2.finlab.finance/blog/python-get-taiwan-stock-data/thumbnail.png) Python 台股 API 比較：FinLab、FinMind、yfinance、證交所 OpenAPI 怎麼選 年化報酬 30.1% · 台股](https://finlab.finance/blog/python-get-taiwan-stock-data)
* [![突破策略回測：QQQ 創 21 日新高＋200 日均線濾網，槓桿 ETF 趨勢跟隨十年實測](https://r2.finlab.finance/blog/us-breakout-trend-strategy/chart5_strategy_equity-202610b.png) 突破策略回測：QQQ 創 21 日新高＋200 日均線濾網，槓桿 ETF 趨勢跟隨十年實測 年化報酬 29.8% · 美股](https://finlab.finance/blog/us-breakout-trend-strategy)

來源：https://finlab.finance/blog/python-auto-trading-gcp-cloud-function｜資料日期：依上文各表格與段落標示｜頁面更新：2026-06-27
