<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	
	xmlns:georss="http://www.georss.org/georss"
	xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
	>

<channel>
	<title>自動交易 &#8211; FinLab</title>
	<atom:link href="https://www.finlab.tw/tag/%E8%87%AA%E5%8B%95%E4%BA%A4%E6%98%93/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.finlab.tw</link>
	<description>深入淺出的量化投資，讓你在在茫茫股海中，找到專屬於自己的投資方法</description>
	<lastBuildDate>Thu, 06 Apr 2023 13:09:44 +0000</lastBuildDate>
	<language>zh-TW</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.9</generator>

<image>
	<url>https://www.finlab.tw/wp-content/uploads/2020/07/favicon.png</url>
	<title>自動交易 &#8211; FinLab</title>
	<link>https://www.finlab.tw</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">179699571</site>	<item>
		<title>3 行 code 自動輸入帳密 Fugle API &#8211; 全自動交易 Fugle 篇</title>
		<link>https://www.finlab.tw/auto-trading-fugle/</link>
					<comments>https://www.finlab.tw/auto-trading-fugle/#respond</comments>
		
		<dc:creator><![CDATA[阿榤]]></dc:creator>
		<pubDate>Sun, 18 Sep 2022 12:47:43 +0000</pubDate>
				<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[選股策略]]></category>
		<category><![CDATA[程式交易]]></category>
		<category><![CDATA[股票]]></category>
		<category><![CDATA[自動交易]]></category>
		<category><![CDATA[量化投資]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=4349</guid>

					<description><![CDATA[<!-- wp:paragraph -->
<p>在先前的<a href="https://www.finlab.tw/auto-trading-part1/" target="_blank" rel="noreferrer noopener">文章</a>中，我們示範了如何使用FinLab串接永豐的API，並上傳至Google Cloud Platform (GCP)，實現全自動交易。</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>考量到也有同學是使用Fugle進行交易，因此決定再寫一篇Fugle版本的教學文章，針對其中不一樣的地方進行演示，希望對大家有所幫助!</p>
<!-- /wp:paragraph -->]]></description>
										<content:encoded><![CDATA[
<h1>前情提要</h1>



<p>在<a href="https://www.finlab.tw/auto-trading-part1/" target="_blank" rel="noreferrer noopener">先前的文章</a>中，我們分兩集示範了如何使用FinLab串接永豐的API，並上傳至Google Cloud Platform (GCP)，實現全自動交易。</p>



<p>近期收到不少同學反應，Fugle由於資安考量，不支持在設定檔中直接設定密碼，而是需要手動輸入，導致沒辦法將Fugle API打包成Cloud Function來執行全自動交易。</p>



<p>(以下截圖來自Fugle 官方文檔)</p>



<figure class="wp-block-image size-full"><img width="711" height="307" src="https://www.finlab.tw/wp-content/uploads/2022/09/image-4.png" alt="Fugle 自動交易限制" class="wp-image-4371" srcset="https://www.finlab.tw/wp-content/uploads/2022/09/image-4.png 711w, https://www.finlab.tw/wp-content/uploads/2022/09/image-4-300x130.png 300w" sizes="(max-width: 711px) 100vw, 711px" title="3 行 code 自動輸入帳密 Fugle API - 全自動交易 Fugle 篇 1"><figcaption><strong>Fugle下單限制</strong></figcaption></figure>



<p>考量到有許多同學使用Fugle交易，我們決定<strong>再寫一篇Fugle版本專屬的教學文章，並破解Fugle所設下的資安防線</strong>，希望對大家有所幫助!</p>



<p>註：本篇文章將著重解說Fugle API與永豐API在串接時的差異，並不會從頭到尾重新講解一遍。建議還沒有看過FinLab與GCP串接教學的同學，先回頭複習更詳細的<a href="https://www.finlab.tw/auto-trading-part1/" target="_blank" rel="noreferrer noopener">教學文章(上)</a>、<a href="https://www.finlab.tw/auto-trading-part2/" target="_blank" rel="noreferrer noopener">教學文章(下)</a>喔！</p>



<h1>免責聲明</h1>



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



<h1>事前準備</h1>



<p>在開始串接Fugle的API之前，有以下幾個步驟必須先完成：</p>



<ol><li>申辦Fugle券商帳戶。</li><li>參照<a href="https://developer.fugle.tw/docs/trading/prerequisites" target="_blank" rel="noreferrer noopener">教學文章１</a>，申請交易API &amp; 完成模擬測試。</li><li>參照<a href="https://developer.fugle.tw/docs/trading/quick_start" target="_blank" rel="noreferrer noopener">教學文章２</a>，送出第一筆委託單。</li></ol>



<p>當你完成上述步驟，就代表你已經能順利使用Fugle的交易API囉！</p>



<p><strong>溫馨提醒：記得把送出的委託單給刪除，才不會不小心成交喔！</strong></p>



<h1>FinLab x Fugle API</h1>



<p>確定Fugle API運作順利後，我們將使用FinLab的內建套件來呼叫Fugle API，達到根據選股清單來進行自動交易。<strong>由於在GCP上面部署要等比較久，我們將分為兩部分測試，先確定在loacl端能順利執行後，再部署到GCP上！</strong></p>



<p>開始之前，請大家先花三分鐘瀏覽有關FinLab下單串接的<a href="https://doc.finlab.tw/details/order_api/" target="_blank" rel="noreferrer noopener">官方文檔</a>，會比較快進入狀況喔！</p>



<h2>本機端自動交易測試</h2>



<h2> 策略生成</h2>



<p>首先要有一個策略，這邊我們同樣使用官方文檔的<a href="https://doc.finlab.tw/tools/%E8%82%A1%E5%83%B9%E5%89%B5%E6%96%B0%E9%AB%98%E5%8B%95%E8%83%BD/" target="_blank" rel="noreferrer noopener">創新高策略</a>示範。</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers"># 生成策略report
import finlab
finlab.login("請填入自己的FINLAB API VIP TOKEN")
from finlab.backtest import sim
from finlab import data
close = data.get("price:收盤價")
position = (close == close.rolling(250).max())
report = sim(position, resample="M",upload=False)</code></pre>



<h2>計算買賣張數</h2>



<p>根據<code>　sim()　</code>回傳的report物件，計算每檔股票所需的買賣張數。</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers"># 輸入投資金額、計算要投資的張數
from finlab.online.order_executor import Position

fund = 100000 #投資金額
position = Position.from_report(report, fund) #產生需要下單的股票清單 &amp; 股數
print(position)</code></pre>



<h2>使用FinLab套件下委託單</h2>



<p>使用FinLab內建的模組，直接呼叫Fugle API執行換股清單的委託單。</p>



<p>註：玉山富果的行情API Token可由登入<a href="https://developer.fugle.tw/docs/key/" target="_blank" rel="noopener">富果API</a>獲得。</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers"># 使用FinLab串接Fugle的進行下單
from finlab.online.order_executor import OrderExecutor
from finlab.online.fugle_account import FugleAccount
import os
os.environ['FUGLE_CONFIG_PATH'] = '玉山富果交易設定檔(config.ini)路徑' 
os.environ['FUGLE_MARKET_API_KEY'] = '玉山富果的行情API Token' # 獲取市價行情以進行下單

acc = FugleAccount()
order_executer = OrderExecutor(position , account=acc)
order_executer.create_orders() # 預設使用最近一筆成交價當成限價</code></pre>



<p>這時候登入Fugle的帳戶中，若有看到委託單即代表本機端的測試成功！</p>



<p>若要取消全部委託單，則可以執行<code>order_executer.cancel_orders()</code>。<a href="https://doc.finlab.tw/details/strategy_dashboard/" target="_blank" rel="noopener"></a></p>



<h2>雲端版本測試</h2>



<p>如同先前教學文章的做法，我們會使用GCP，把在Local端測試好的程式碼打包成函式，以Cloud Function的方式呼叫。</p>



<p>接下來主要會講解Fugle和永豐在串接上不同的部分，其餘絕大部分相同的步驟請同學自行參照<a href="https://www.finlab.tw/auto-trading-part2/" target="_blank" rel="noreferrer noopener">教學文章(下)</a>。</p>



<h3>上傳憑證</h3>



<p>首先建立一個bucket(值區)，但這時候要上傳的東西變成<strong>兩個</strong>：</p>



<ol><li>config.ini 設定檔</li><li>交易憑證(.p12檔案)</li></ol>



<p>註：為了清楚的demo，<strong>接下來的示範將預設採用以下統一命名</strong>，大家可以自行決定是否要採用一樣的命名方式。</p>



<ul><li>bucket名稱：fugle_pass</li><li>環境設定檔名：config.ini</li><li>憑證檔名：fugle_cert.p12</li></ul>



<p class="has-vivid-red-color has-text-color"><strong>設定檔和憑證都會在事前準備階段時取得。但在上傳前，請記得將config.ini設定檔當中的憑證路徑改成GCP上的路徑，否則GCP會抓不到你的交易憑證。</strong></p>



<figure class="wp-block-image size-full"><img loading="lazy" width="858" height="193" src="https://www.finlab.tw/wp-content/uploads/2022/09/image-8.png" alt="image 8" class="wp-image-4378" srcset="https://www.finlab.tw/wp-content/uploads/2022/09/image-8.png 858w, https://www.finlab.tw/wp-content/uploads/2022/09/image-8-300x67.png 300w, https://www.finlab.tw/wp-content/uploads/2022/09/image-8-768x173.png 768w" sizes="(max-width: 858px) 100vw, 858px" title="3 行 code 自動輸入帳密 Fugle API - 全自動交易 Fugle 篇 2"><figcaption><strong>修改config.ini設定檔</strong></figcaption></figure>



<h3>環境變數設定</h3>



<p>這邊我們要填入所需的環境變數，<strong>變數Value1~Value6需要自己填寫</strong>，Value7則複製<code>keyrings.cryptfile.cryptfile.CryptFileKeyring</code> 即可。</p>



<figure class="wp-block-image size-full"><img loading="lazy" width="798" height="572" src="https://www.finlab.tw/wp-content/uploads/2022/11/image.png" alt="image" class="wp-image-4863" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/image.png 798w, https://www.finlab.tw/wp-content/uploads/2022/11/image-300x215.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/image-768x550.png 768w" sizes="(max-width: 798px) 100vw, 798px" title="3 行 code 自動輸入帳密 Fugle API - 全自動交易 Fugle 篇 3"><figcaption><strong>環境變數設定</strong></figcaption></figure>



<p>註：打開config.ini設定檔查看其中的[User]欄位，即可找到自己的Fugle帳號。</p>



<h3>程式碼設定</h3>



<p>與之前的<a href="https://www.finlab.tw/auto-trading-part2/" target="_blank" rel="noreferrer noopener">教學文</a>相同，我們將分為以下五個檔案，其中的<code>main.py</code>和<code>run_strategy.py</code>完全一樣，這邊就不贅述了。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="625" src="https://www.finlab.tw/wp-content/uploads/2022/08/12-1024x625.png" alt="12" class="wp-image-4277" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/12-1024x625.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/08/12-300x183.png 300w, https://www.finlab.tw/wp-content/uploads/2022/08/12-768x469.png 768w, https://www.finlab.tw/wp-content/uploads/2022/08/12.png 1086w" sizes="(max-width: 1024px) 100vw, 1024px" title="3 行 code 自動輸入帳密 Fugle API - 全自動交易 Fugle 篇 4"><figcaption><strong>程式碼初始設定</strong></figcaption></figure>



<h3>requirements.txt</h3>



<p>將原先的<code>shioaji</code>安裝包換成<code>fugle_trade</code>，另外為了破解Fugle的資安防線，要再加入一個叫<code>keyring</code>的套件，其功用是拿來儲存帳號密碼。</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers"># Function dependencies, for example:
# package&gt;=version
finlab==0.3.7.dev1
fugle_trade==0.3.1
keyring==23.5.0
google-cloud-storage</code></pre>



<h3>bucket.py</h3>



<p>從<code>fugle pass</code>的bucket中，將<code>fugle_cert.p12</code>和<code>config.ini</code>移到<code>/tmp</code>目錄底下。</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">from google.cloud import storage

# 將需要用到的檔案從bucket移到/tmp目錄底下
def connect_storage():
  storage_client = storage.Client()
  bucket = storage_client.bucket('fugle_pass')
  blob = bucket.blob("fugle_cert.p12")
  blob.download_to_filename('/tmp/fugle_cert.p12')  
  blob = bucket.blob("config.ini")
  blob.download_to_filename('/tmp/config.ini')  
  return</code></pre>



<h3>make_order.py</h3>



<p>接下來就是最重要的問題點啦！因為Fugle強制要求在第一次使用時要親手key密碼才行，這樣就導致沒辦法在Clound Function上自動執行。</p>



<p>我仔細地翻閱了fugle-trade 套件的原始碼，發現Fugle在初始SDK物件時，會透過keyring這個套件，執行自定義的function去檢查是否有已存在的帳密(非第一次登入。若是第一次登入，就必須強制使用者重新輸入密碼。</p>



<p>同時他們還透過hashcode，對每個人的帳號進行hash之後作為keyring的backend，讓破解起來更為麻煩。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="537" src="https://www.finlab.tw/wp-content/uploads/2022/09/Inkedcode-1024x537.jpg" alt="Inkedcode" class="wp-image-4381" srcset="https://www.finlab.tw/wp-content/uploads/2022/09/Inkedcode-1024x537.jpg 1024w, https://www.finlab.tw/wp-content/uploads/2022/09/Inkedcode-300x157.jpg 300w, https://www.finlab.tw/wp-content/uploads/2022/09/Inkedcode-768x403.jpg 768w, https://www.finlab.tw/wp-content/uploads/2022/09/Inkedcode.jpg 1408w" sizes="(max-width: 1024px) 100vw, 1024px" title="3 行 code 自動輸入帳密 Fugle API - 全自動交易 Fugle 篇 5"><figcaption><strong>fugle-trade 內部程式碼</strong></figcaption></figure>



<p>以上算是比較細部的講解，大家有興趣也可以去翻翻看Fugle的程式碼。</p>



<p class="has-vivid-red-color has-text-color">看不懂也沒關係，FinLab都幫大家處理好了，只需要跟著以下步驟，加入三行程式碼即可！</p>



<p><strong>首先，引入需使用的套件。</strong></p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="217" src="https://www.finlab.tw/wp-content/uploads/2022/09/code-1024x217.png" alt="code" class="wp-image-4427" srcset="https://www.finlab.tw/wp-content/uploads/2022/09/code-1024x217.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/09/code-300x63.png 300w, https://www.finlab.tw/wp-content/uploads/2022/09/code-768x162.png 768w, https://www.finlab.tw/wp-content/uploads/2022/09/code.png 1154w" sizes="(max-width: 1024px) 100vw, 1024px" title="3 行 code 自動輸入帳密 Fugle API - 全自動交易 Fugle 篇 6"><figcaption><strong>import 所需套件</strong></figcaption></figure>



<p><strong>在<code>acc = FugleAccount()</code>前，插入以下三行程式碼。</strong></p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="328" src="https://www.finlab.tw/wp-content/uploads/2022/09/code2-2-1024x328.png" alt="code2 2" class="wp-image-4388" srcset="https://www.finlab.tw/wp-content/uploads/2022/09/code2-2-1024x328.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/09/code2-2-300x96.png 300w, https://www.finlab.tw/wp-content/uploads/2022/09/code2-2-768x246.png 768w, https://www.finlab.tw/wp-content/uploads/2022/09/code2-2.png 1356w" sizes="(max-width: 1024px) 100vw, 1024px" title="3 行 code 自動輸入帳密 Fugle API - 全自動交易 Fugle 篇 7"><figcaption><strong>精華的三行程式碼!</strong></figcaption></figure>



<p>大功告成！就這麼簡單，核心概念是在Fugle的SDK初始化之前，搶先呼叫Fugle自己的函式執行了「預登入」的動作。因此Fugle在初始化檢查的時候，就不會出現需要手動輸入密碼的問題囉！</p>



<p>以下附上完整的程式碼，大家可以直接拿去使用，再更動裡面的參數，就可以實現不同的資金量和下單方式囉!</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">import os
os.chdir("/tmp")
import keyring
import time
from fugle_trade.util import setup_keyring
from finlab.online.order_executor import Position
from finlab.online.order_executor import OrderExecutor
from finlab.online.fugle_account import FugleAccount

def make_order(report,fund=100000):
    position = Position.from_report(report, fund,odd_lot=False)
    setup_keyring(os.environ["FUGLE_ACCOUNT"])
    keyring.set_password("fugle_trade_sdk:account", os.environ["FUGLE_ACCOUNT"], os.environ["FUGLE_ACCOUNT_PASSWORD"])
    keyring.set_password("fugle_trade_sdk:cert", os.environ["FUGLE_ACCOUNT"], os.environ["FUGLE_CERT_PASSWORD"])
    acc = FugleAccount()
    order_executer = OrderExecutor(position , account=acc)
    order_executer.create_orders() # 預設使用最近一筆成交價當成限價
    # 利用預先下單，回傳下單資訊至網頁以供瀏覽 (以下可以全拿掉，留一個return即可)
    time.sleep(10) #Fugle限制兩次之間要間隔十秒
    record = order_executer.create_orders(view_only=True)
    key_list = [i for i in range(1,len(record)+1)]
    value_list = [{i['stock_id']:i['quantity']} for i in record]
    return dict(zip(key_list, value_list))</code></pre>



<p>解決了關鍵問題後，其餘步驟就和永豐篇的<a href="https://www.finlab.tw/auto-trading-part2/" target="_blank" rel="noreferrer noopener">教學文章</a>完全相同啦，這邊就不多贅述了！</p>



<h2>Colab 版本下單</h2>



<p>若在雲端部署上遇到困難，歡迎到<a href="https://discord.gg/TwNAqsM8uQ" target="_blank" rel="noreferrer noopener">Discord</a>詢問我們，另外我們也提供了<a href="https://colab.research.google.com/drive/10xK0VsTBKtO763i7SelAseNMWCHyfQ81?usp=sharing" target="_blank" rel="noreferrer noopener">Colab下單腳本</a>給大家，歡迎大家依照自己的需求選擇！</p>



<h1>小彩蛋（零股語法糖）</h1>



<p class="has-vivid-red-color has-text-color">想必眼尖的大家已經注意到了，我們同時實作了零股下單的功能！</p>



<p class="has-black-color has-text-color"><strong>只要把<code>Position.from_report(report, fund,odd_lot=False)</code>的odd_lot變數改為True，就會變成零股下單模式囉！</strong></p>



<p>這是考量到資金量較小、或策略較多的學員所設計的。目前不管永豐、Fugle目前都有零股最低手續費1元的優惠，可以最大限度地降低摩擦的手續費，讓零股盡可能貼近和整股相同的績效，希望大家會喜歡！</p>



<h1>結論</h1>



<p>這篇文章中，<strong>我們破解了Fugle API的限制</strong>，成功將下單函式部署在GCP上執行，讓永豐跟Fugle的FinLab用戶們都能獲得一樣的體驗。</p>



<p><strong>同時我們設計了小資族友善的「零股模式」</strong>。希望從資金方面、技術方面，都能盡量降低大家實踐程式交易的門檻。</p>



<p>FinLab是個熱愛與使用者互動的團隊，同時會積極考慮將用戶需求納入下一步的更新規劃，也因此需要更多來自大家的feedback！如果大家喜歡這篇文章，或有任何的想法想要告訴我們，就趕快到<a href="https://www.facebook.com/finlab.python" target="_blank" rel="noreferrer noopener">粉絲專頁</a>留言吧！</p>



<p>這次的教學就這樣告一段落了。我是阿榤，下次見，掰！(⁎⁍̴̛ᴗ⁍̴̛⁎)</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/auto-trading-fugle/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4349</post-id>	</item>
		<item>
		<title>FinLab x Google雲端平台 &#124; 3步驟實現Python全自動交易，從今以後躺著都能賺！(下)</title>
		<link>https://www.finlab.tw/auto-trading-part2/</link>
					<comments>https://www.finlab.tw/auto-trading-part2/#respond</comments>
		
		<dc:creator><![CDATA[阿榤]]></dc:creator>
		<pubDate>Wed, 31 Aug 2022 10:03:04 +0000</pubDate>
				<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[選股策略]]></category>
		<category><![CDATA[程式交易]]></category>
		<category><![CDATA[股票]]></category>
		<category><![CDATA[自動交易]]></category>
		<category><![CDATA[量化投資]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=4249</guid>

					<description><![CDATA[<!-- wp:paragraph -->
<p>在自動交易的<a href="https://www.finlab.tw/auto-trading-part1/" target="_blank" rel="noreferrer noopener">上集</a>中，我們完成了永豐和FinLab相關的前置作頁，包括申請交易憑證、打包策略程式碼、加入下單模組。</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>在本篇<a href="https://www.finlab.tw/auto-trading-part2/">文章</a>中，我們會將這些東西上傳到GCP以完成Cloud Function部署，最後用Cloud Scheduler定期呼叫Cloud Function，這樣一切就大功告成了！</p>
<!-- /wp:paragraph -->]]></description>
										<content:encoded><![CDATA[
<h1>前情提要</h1>



<p>在自動交易的<a href="https://www.finlab.tw/auto-trading-part1/" target="_blank" rel="noreferrer noopener">上集</a>中，我們完成了永豐和FinLab相關的前置作頁，包括申請交易憑證、打包策略程式碼、加入下單模組。</p>



<p>在本篇<a href="https://www.finlab.tw/auto-trading-part2/">文章</a>中，我們會將這些東西上傳到GCP以完成Cloud Function部署，最後用Cloud Scheduler定期呼叫Cloud Function，這樣一切就大功告成了！</p>



<h2>流程圖</h2>



<p>附上流程圖幫大家複習一下，如果沒有看過<a href="https://www.finlab.tw/auto-trading-part1/" target="_blank" rel="noreferrer noopener">上集</a>的同學，記得先回去補課喔！</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="594" src="https://www.finlab.tw/wp-content/uploads/2022/08/Untitled-1-1024x594.png" alt="自動交易設定流程圖" class="wp-image-4263" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/Untitled-1-1024x594.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/08/Untitled-1-300x174.png 300w, https://www.finlab.tw/wp-content/uploads/2022/08/Untitled-1-768x446.png 768w, https://www.finlab.tw/wp-content/uploads/2022/08/Untitled-1-1536x891.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/08/Untitled-1.png 2040w" sizes="(max-width: 1024px) 100vw, 1024px" title="FinLab x Google雲端平台 | 3步驟實現Python全自動交易，從今以後躺著都能賺！(下) 8"><figcaption>自動交易設定流程圖</figcaption></figure>



<h1>免責聲明</h1>



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



<h1>Google Cloud Platform (GCP)</h1>



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



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



<ul><li>Cloud Storage：雲端的儲存空間，用來存放永豐的交易憑證</li><li>Cloud Function：雲端執行FinLab選股策略和下單程式碼。</li><li>Cloud Sceduler：雲端排程工具，定期執行部署的Cloud Function。</li></ul>



<h2>GCP 要收費嗎?</h2>



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



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



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



<p>有疑問的同學可以到 <a href="https://cloud.google.com/functions/pricing" target="_blank" rel="noreferrer noopener">Google cloud function 的定價</a>來查看更詳細的定價，接下來就讓我們開始吧！</p>



<h2>註冊帳號</h2>



<p>首先到GCP的<a href="https://cloud.google.com/landing/free-trial?hl=zh-tw&amp;utm_source=google&amp;utm_medium=cpc&amp;utm_campaign=japac-TW-all-zh-dr-bkws-all-all-trial-e-dr-1009882&amp;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&amp;userloc_1012818-network_g&amp;utm_term=KW_gcp&amp;gclid=CjwKCAjwx7GYBhB7EiwA0d8oezDlAskppfC9tDF2fuA7B7Pnms9567QnsT4wjeSyyJLr1Z6SrE14vxoCHroQAvD_BwE&amp;gclsrc=aw.ds" target="_blank" rel="noreferrer noopener">官網</a>註冊一個帳號，註冊表單按照自己的狀況填即可。</p>



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



<h2>新增專案</h2>



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



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="355" src="https://www.finlab.tw/wp-content/uploads/2022/08/2-1024x355.png" alt="2" class="wp-image-4267" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/2-1024x355.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/08/2-300x104.png 300w, https://www.finlab.tw/wp-content/uploads/2022/08/2-768x266.png 768w, https://www.finlab.tw/wp-content/uploads/2022/08/2.png 1458w" sizes="(max-width: 1024px) 100vw, 1024px" title="FinLab x Google雲端平台 | 3步驟實現Python全自動交易，從今以後躺著都能賺！(下) 9"></figure>



<figure class="wp-block-image size-full"><img loading="lazy" width="813" height="667" src="https://www.finlab.tw/wp-content/uploads/2022/08/3-1.png" alt="3 1" class="wp-image-4313" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/3-1.png 813w, https://www.finlab.tw/wp-content/uploads/2022/08/3-1-300x246.png 300w, https://www.finlab.tw/wp-content/uploads/2022/08/3-1-768x630.png 768w" sizes="(max-width: 813px) 100vw, 813px" title="FinLab x Google雲端平台 | 3步驟實現Python全自動交易，從今以後躺著都能賺！(下) 10"></figure>



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



<h2>上傳交易憑證</h2>



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



<figure class="wp-block-image size-full"><img loading="lazy" width="714" height="373" src="https://www.finlab.tw/wp-content/uploads/2022/08/4.png" alt="4" class="wp-image-4269" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/4.png 714w, https://www.finlab.tw/wp-content/uploads/2022/08/4-300x157.png 300w" sizes="(max-width: 714px) 100vw, 714px" title="FinLab x Google雲端平台 | 3步驟實現Python全自動交易，從今以後躺著都能賺！(下) 11"></figure>



<p>值區名稱可以自行設定，我這邊設定為trading_pass。</p>



<figure class="wp-block-image size-full"><img loading="lazy" width="734" height="479" src="https://www.finlab.tw/wp-content/uploads/2022/08/5.png" alt="5" class="wp-image-4270" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/5.png 734w, https://www.finlab.tw/wp-content/uploads/2022/08/5-300x196.png 300w" sizes="(max-width: 734px) 100vw, 734px" title="FinLab x Google雲端平台 | 3步驟實現Python全自動交易，從今以後躺著都能賺！(下) 12"></figure>



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



<figure class="wp-block-image size-full"><img loading="lazy" width="790" height="571" src="https://www.finlab.tw/wp-content/uploads/2022/08/6.png" alt="6" class="wp-image-4271" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/6.png 790w, https://www.finlab.tw/wp-content/uploads/2022/08/6-300x217.png 300w, https://www.finlab.tw/wp-content/uploads/2022/08/6-768x555.png 768w" sizes="(max-width: 790px) 100vw, 790px" title="FinLab x Google雲端平台 | 3步驟實現Python全自動交易，從今以後躺著都能賺！(下) 13"></figure>



<h2>部署 Cloud Function</h2>



<h3>啟用API</h3>



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



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="535" src="https://www.finlab.tw/wp-content/uploads/2022/08/7-1024x535.png" alt="7" class="wp-image-4272" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/7-1024x535.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/08/7-300x157.png 300w, https://www.finlab.tw/wp-content/uploads/2022/08/7-768x401.png 768w, https://www.finlab.tw/wp-content/uploads/2022/08/7.png 1342w" sizes="(max-width: 1024px) 100vw, 1024px" title="FinLab x Google雲端平台 | 3步驟實現Python全自動交易，從今以後躺著都能賺！(下) 14"></figure>



<h3>基本設定</h3>



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



<figure class="wp-block-image size-full"><img loading="lazy" width="804" height="425" src="https://www.finlab.tw/wp-content/uploads/2022/08/8.png" alt="8" class="wp-image-4273" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/8.png 804w, https://www.finlab.tw/wp-content/uploads/2022/08/8-300x159.png 300w, https://www.finlab.tw/wp-content/uploads/2022/08/8-768x406.png 768w" sizes="(max-width: 804px) 100vw, 804px" title="FinLab x Google雲端平台 | 3步驟實現Python全自動交易，從今以後躺著都能賺！(下) 15"></figure>



<h3>觸發條件設定</h3>



<figure class="wp-block-image size-full"><img loading="lazy" width="790" height="618" src="https://www.finlab.tw/wp-content/uploads/2022/08/9.png" alt="9" class="wp-image-4274" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/9.png 790w, https://www.finlab.tw/wp-content/uploads/2022/08/9-300x235.png 300w, https://www.finlab.tw/wp-content/uploads/2022/08/9-768x601.png 768w" sizes="(max-width: 790px) 100vw, 790px" title="FinLab x Google雲端平台 | 3步驟實現Python全自動交易，從今以後躺著都能賺！(下) 16"></figure>



<h3>記憶體和時間配置設定</h3>



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



<figure class="wp-block-image size-full"><img loading="lazy" width="791" height="314" src="https://www.finlab.tw/wp-content/uploads/2022/08/10.png" alt="10" class="wp-image-4275" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/10.png 791w, https://www.finlab.tw/wp-content/uploads/2022/08/10-300x119.png 300w, https://www.finlab.tw/wp-content/uploads/2022/08/10-768x305.png 768w" sizes="(max-width: 791px) 100vw, 791px" title="FinLab x Google雲端平台 | 3步驟實現Python全自動交易，從今以後躺著都能賺！(下) 17"></figure>



<h3>環境變數設定</h3>



<p>環境變數的有四個值要改成自己的，作為登入永豐和FinLab驗證用。</p>



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



<figure class="wp-block-image size-full"><img loading="lazy" width="743" height="532" src="https://www.finlab.tw/wp-content/uploads/2022/10/image.png" alt="image" class="wp-image-4631" srcset="https://www.finlab.tw/wp-content/uploads/2022/10/image.png 743w, https://www.finlab.tw/wp-content/uploads/2022/10/image-300x215.png 300w" sizes="(max-width: 743px) 100vw, 743px" title="FinLab x Google雲端平台 | 3步驟實現Python全自動交易，從今以後躺著都能賺！(下) 18"><figcaption><strong>環境變數設置</strong></figcaption></figure>



<h3>程式碼初始設定</h3>



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



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



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="625" src="https://www.finlab.tw/wp-content/uploads/2022/08/12-1024x625.png" alt="12" class="wp-image-4277" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/12-1024x625.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/08/12-300x183.png 300w, https://www.finlab.tw/wp-content/uploads/2022/08/12-768x469.png 768w, https://www.finlab.tw/wp-content/uploads/2022/08/12.png 1086w" sizes="(max-width: 1024px) 100vw, 1024px" title="FinLab x Google雲端平台 | 3步驟實現Python全自動交易，從今以後躺著都能賺！(下) 19"></figure>



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



<h3>run_strategy.py</h3>



<p>將我們上面打包好的function，引入環境變數中的FinLab token，將FinLab登入的動作也寫在code裡面。</p>



<pre class="wp-block-code"><code lang="python" class="language-python">import finlab
import os
finlab.login(os.environ["FINLAB_API_TOKEN"])
from finlab.backtest import sim
from finlab import data

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
</code></pre>



<h3>make_order.py</h3>



<p>首先請大家先看過<a href="https://doc.finlab.tw/details/order_api/" target="_blank" rel="noreferrer noopener">FinLab官方文檔</a>，會比較能理解下方的程式碼。</p>



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



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



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



<pre class="wp-block-code"><code lang="python" class="language-python">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))
</code></pre>



<h3>bucket.py</h3>



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



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



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



<pre class="wp-block-code"><code lang="python" class="language-python">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
</code></pre>



<h3>main.py</h3>



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



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



<pre class="wp-block-code"><code lang="python" class="language-python">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
</code></pre>



<h3>requirements.txt</h3>



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



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



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



<p></p>



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



<pre class="wp-block-code"><code lang="python" class="language-python"># 假設你不知道自己使用的shioaji套件版本
import shioaji
print(shioaji.__version__) #印出套件的版本
# 輸出: 0.3.6.dev2 =&gt; 這就是你的shioaji套件版本</code></pre>



<p></p>



<h3>上傳Cloud Function</h3>



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



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="161" src="https://www.finlab.tw/wp-content/uploads/2022/08/13-1024x161.png" alt="13" class="wp-image-4280" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/13-1024x161.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/08/13-300x47.png 300w, https://www.finlab.tw/wp-content/uploads/2022/08/13-768x120.png 768w, https://www.finlab.tw/wp-content/uploads/2022/08/13.png 1492w" sizes="(max-width: 1024px) 100vw, 1024px" title="FinLab x Google雲端平台 | 3步驟實現Python全自動交易，從今以後躺著都能賺！(下) 20"></figure>



<h3>權限說明</h3>



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



<figure class="wp-block-image size-full"><img loading="lazy" width="729" height="497" src="https://www.finlab.tw/wp-content/uploads/2022/08/14.png" alt="14" class="wp-image-4281" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/14.png 729w, https://www.finlab.tw/wp-content/uploads/2022/08/14-300x205.png 300w" sizes="(max-width: 729px) 100vw, 729px" title="FinLab x Google雲端平台 | 3步驟實現Python全自動交易，從今以後躺著都能賺！(下) 21"></figure>



<h3>Cloud Function測試</h3>



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



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



<figure class="wp-block-image size-full"><img loading="lazy" width="784" height="443" src="https://www.finlab.tw/wp-content/uploads/2022/08/15.png" alt="15" class="wp-image-4282" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/15.png 784w, https://www.finlab.tw/wp-content/uploads/2022/08/15-300x170.png 300w, https://www.finlab.tw/wp-content/uploads/2022/08/15-768x434.png 768w" sizes="(max-width: 784px) 100vw, 784px" title="FinLab x Google雲端平台 | 3步驟實現Python全自動交易，從今以後躺著都能賺！(下) 22"></figure>



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



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



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



<figure class="wp-block-image size-full"><img loading="lazy" width="444" height="255" src="https://www.finlab.tw/wp-content/uploads/2022/08/16.png" alt="16" class="wp-image-4283" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/16.png 444w, https://www.finlab.tw/wp-content/uploads/2022/08/16-300x172.png 300w" sizes="(max-width: 444px) 100vw, 444px" title="FinLab x Google雲端平台 | 3步驟實現Python全自動交易，從今以後躺著都能賺！(下) 23"></figure>



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



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="294" src="https://www.finlab.tw/wp-content/uploads/2022/08/image-6-1024x294.png" alt="image 6" class="wp-image-4287" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/image-6-1024x294.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/08/image-6-300x86.png 300w, https://www.finlab.tw/wp-content/uploads/2022/08/image-6-768x221.png 768w, https://www.finlab.tw/wp-content/uploads/2022/08/image-6-1536x442.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/08/image-6.png 1840w" sizes="(max-width: 1024px) 100vw, 1024px" title="FinLab x Google雲端平台 | 3步驟實現Python全自動交易，從今以後躺著都能賺！(下) 24"></figure>



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



<h2>設定 Cloud Scheduler</h2>



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



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



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



<figure class="wp-block-image size-full"><img loading="lazy" width="748" height="714" src="https://www.finlab.tw/wp-content/uploads/2022/08/17.png" alt="17" class="wp-image-4284" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/17.png 748w, https://www.finlab.tw/wp-content/uploads/2022/08/17-300x286.png 300w" sizes="(max-width: 748px) 100vw, 748px" title="FinLab x Google雲端平台 | 3步驟實現Python全自動交易，從今以後躺著都能賺！(下) 25"></figure>



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



<figure class="wp-block-image size-full"><img loading="lazy" width="744" height="610" src="https://www.finlab.tw/wp-content/uploads/2022/08/18.png" alt="18" class="wp-image-4285" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/18.png 744w, https://www.finlab.tw/wp-content/uploads/2022/08/18-300x246.png 300w" sizes="(max-width: 744px) 100vw, 744px" title="FinLab x Google雲端平台 | 3步驟實現Python全自動交易，從今以後躺著都能賺！(下) 26"></figure>



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



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="240" src="https://www.finlab.tw/wp-content/uploads/2022/08/19-1024x240.png" alt="19" class="wp-image-4286" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/19-1024x240.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/08/19-300x70.png 300w, https://www.finlab.tw/wp-content/uploads/2022/08/19-768x180.png 768w, https://www.finlab.tw/wp-content/uploads/2022/08/19-1536x361.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/08/19.png 1849w" sizes="(max-width: 1024px) 100vw, 1024px" title="FinLab x Google雲端平台 | 3步驟實現Python全自動交易，從今以後躺著都能賺！(下) 27"></figure>



<h2>Colab 版本下單</h2>



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



<h2>溫馨提醒</h2>



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



<h1>總結</h1>



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



<p>祝大家一切順利，天天在家睏飽數錢，有任何問題也歡迎在文章下方或到<a href="https://www.facebook.com/finlab.python" target="_blank" rel="noreferrer noopener">FinLab粉專</a>留言！</p>



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



<h1>(2023/4/6 更新) Shioaji Version &gt;= 1.0 環境變數設定</h1>



<p>因應永豐更新主要版本至1.0，採用了全新驗證方式。若要使用1.0以後的版本，請先到<a href="https://sinotrade.github.io/tutor/prepare/token/" target="_blank" rel="noreferrer noopener">永豐官網</a>申請API，將權限設置如下。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="448" src="https://www.finlab.tw/wp-content/uploads/2023/04/image-2-1024x448.png" alt="image 2" class="wp-image-5348" srcset="https://www.finlab.tw/wp-content/uploads/2023/04/image-2-1024x448.png 1024w, https://www.finlab.tw/wp-content/uploads/2023/04/image-2-300x131.png 300w, https://www.finlab.tw/wp-content/uploads/2023/04/image-2-768x336.png 768w, https://www.finlab.tw/wp-content/uploads/2023/04/image-2.png 1167w" sizes="(max-width: 1024px) 100vw, 1024px" title="FinLab x Google雲端平台 | 3步驟實現Python全自動交易，從今以後躺著都能賺！(下) 28"></figure>



<p>請將環境變數的設置改為以下</p>



<figure class="wp-block-image size-full"><img loading="lazy" width="727" height="522" src="https://www.finlab.tw/wp-content/uploads/2023/04/image-1.png" alt="image 1" class="wp-image-5345" srcset="https://www.finlab.tw/wp-content/uploads/2023/04/image-1.png 727w, https://www.finlab.tw/wp-content/uploads/2023/04/image-1-300x215.png 300w" sizes="(max-width: 727px) 100vw, 727px" title="FinLab x Google雲端平台 | 3步驟實現Python全自動交易，從今以後躺著都能賺！(下) 29"><figcaption><strong>Shioaji 1.0版本以後的環境變數設定</strong></figcaption></figure>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/auto-trading-part2/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4249</post-id>	</item>
		<item>
		<title>FinLab x Google雲端平台 &#124; 3步驟實現全自動交易，從今以後躺著都能賺！(上)</title>
		<link>https://www.finlab.tw/auto-trading-part1/</link>
					<comments>https://www.finlab.tw/auto-trading-part1/#respond</comments>
		
		<dc:creator><![CDATA[阿榤]]></dc:creator>
		<pubDate>Wed, 31 Aug 2022 02:58:55 +0000</pubDate>
				<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[選股策略]]></category>
		<category><![CDATA[程式交易]]></category>
		<category><![CDATA[股票]]></category>
		<category><![CDATA[自動交易]]></category>
		<category><![CDATA[量化投資]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=4228</guid>

					<description><![CDATA[<!-- wp:paragraph -->
<p>前陣子在FB粉專發的，<a href="https://www.facebook.com/finlab.python/posts/pfbid022tepWjpiQwqw5H7fCeuL1BFVEhsvnhsmjG6NGFYLTW1vwmmj2oL1Y5abmHg7qYrrl" target="_blank" rel="noreferrer noopener">【從零開始！10萬塊開局的程式交易實戰週記】 EP4 - <img height="16" width="16" src="https://static.xx.fbcdn.net/images/emoji.php/v9/td1/1.5/16/33_20e3.png" alt="3️⃣">步驟達成全自動買賣！</a>受到大家的廣泛迴響，因此我寫了一篇串接自動交易的完整教學，希望對大家有所幫助！</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>本篇<a href="https://www.finlab.tw/auto-trading-part1/">文章</a>將會帶大家瞭解，如何將寫好的FinLab選股策略上傳至雲端，進行全自動的交易。讓電腦連你在睡覺時，都能幫你交易賺錢，再也不用天天盯盤手動下單了，實現真正所謂的躺著賺XD</p>
<!-- /wp:paragraph -->]]></description>
										<content:encoded><![CDATA[
<h1>前情提要</h1>



<p>前陣子在FB粉專發的，<a href="https://www.facebook.com/finlab.python/posts/pfbid022tepWjpiQwqw5H7fCeuL1BFVEhsvnhsmjG6NGFYLTW1vwmmj2oL1Y5abmHg7qYrrl" target="_blank" rel="noreferrer noopener">【從零開始！10萬塊開局的程式交易實戰週記】 EP4 &#8211; <img loading="lazy" height="16" width="16" src="https://static.xx.fbcdn.net/images/emoji.php/v9/td1/1.5/16/33_20e3.png" alt="3&#xfe0f;&#x20e3;" title="FinLab x Google雲端平台 | 3步驟實現全自動交易，從今以後躺著都能賺！(上) 30">步驟達成全自動買賣！</a>受到大家的廣泛迴響，因此我寫了一篇串接自動交易的完整教學，希望對大家有所幫助！</p>



<p>本篇<a href="https://www.finlab.tw/auto-trading-part1/">文章</a>將會帶大家瞭解，如何將寫好的FinLab選股策略上傳至雲端，進行全自動的交易。讓電腦連你在睡覺時，都能幫你交易賺錢，再也不用天天盯盤手動下單了，實現真正所謂的躺著賺XD</p>



<h1>免責聲明</h1>



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



<h1>流程簡介</h1>



<p>FinLab目前支援的券商有永豐和Fugle，此篇將以永豐帳戶作為示範。</p>



<p>設定全自動交易的流程主要分為三個部分：永豐、FinLab、Google Cloud Platform(GCP)。永豐的部份，我們需要申請一個交易帳戶，並簽署有關API下單的同意書後，申請交易憑證並記好檔案存放的位置，以便之後要上傳到GCP。</p>



<p>FinLab部分則只需要把寫好的策略包裝成function的形式即可。</p>



<p>最後一步是部署選股策略在GCP上，這時候我們需要將前面拿到的交易憑證、包裝好的策略函式分別上傳到GCP進行佈署，最後再用Cloud Scheduler設定固定執行策略的時間，就完成所有的設定了!</p>



<h2>完整流程圖</h2>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="594" src="https://www.finlab.tw/wp-content/uploads/2022/08/Untitled-1024x594.png" alt="全自動交易流程圖" class="wp-image-4234" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/Untitled-1024x594.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/08/Untitled-300x174.png 300w, https://www.finlab.tw/wp-content/uploads/2022/08/Untitled-768x446.png 768w, https://www.finlab.tw/wp-content/uploads/2022/08/Untitled-1536x891.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/08/Untitled.png 2040w" sizes="(max-width: 1024px) 100vw, 1024px" title="FinLab x Google雲端平台 | 3步驟實現全自動交易，從今以後躺著都能賺！(上) 31"><figcaption>自動交易設定流程圖</figcaption></figure>



<h1>名詞解釋</h1>



<p>在教學開始前對一些重要名詞做了簡短的解釋，希望讓大家更容易吸收文章內容。</p>



<ul><li>交易憑證：一個.pfx結尾的檔案，電子下單時系統會檢查此憑證，必須有正確的憑證才可以下單。</li><li>Google Cloud Platform(GCP)：Google的雲端平台，有著一系列由Google提供的雲端運算服務。<ul><li>Cloud Storage：雲端的儲存空間。</li></ul><ul><li>Cloud Function：將函式上傳到雲端執行，而不用在本機端執行。</li></ul><ul><li>Cloud Scheduler：配合Cloud Function使用，可設定在固定時間點執行特定的Cloud Function。</li></ul></li></ul>



<p>接下來我會針對永豐、FinLab、GCP，一步步跟大家說明操作步驟。</p>



<h1>永豐</h1>



<p>首先是券商方面的設定，全程都不需撰寫程式。如果在過程中遇到問題，記得直接向自己的營業員詢問最快喔！</p>



<h2>開永豐/Fugle證券戶</h2>



<p>這兩家券商是目前FinLab模組有支援的券商，但因為本文是用永豐的帳戶來示範，如果想要一步一步跟著做的話，建議還是申辦永豐的券商。兩家券商都可以在線上進行開戶，這邊就不多贅述。</p>



<h2>簽署API證券下單同意書</h2>



<p>開完戶之後，按照營業員指示簽完基本的同意書後，記的要多簽一個API證券下單簽署，才能用API進行下單喔！</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="479" src="https://www.finlab.tw/wp-content/uploads/2022/08/1-2-1024x479.png" alt="1 2" class="wp-image-4241" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/1-2-1024x479.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/08/1-2-300x140.png 300w, https://www.finlab.tw/wp-content/uploads/2022/08/1-2-768x359.png 768w, https://www.finlab.tw/wp-content/uploads/2022/08/1-2.png 1369w" sizes="(max-width: 1024px) 100vw, 1024px" title="FinLab x Google雲端平台 | 3步驟實現全自動交易，從今以後躺著都能賺！(上) 32"></figure>



<h2>申請下單憑證</h2>



<p>下載<a href="https://www.sinotrade.com.tw/UploadFiles/TCEM_SINO_PROD.exe" target="_blank" rel="noreferrer noopener">憑證管理小AP</a> ，打開後會看以下到畫面</p>



<figure class="wp-block-image size-full"><img loading="lazy" width="957" height="794" src="https://www.finlab.tw/wp-content/uploads/2022/08/2-2.png" alt="2 2" class="wp-image-4242" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/2-2.png 957w, https://www.finlab.tw/wp-content/uploads/2022/08/2-2-300x249.png 300w, https://www.finlab.tw/wp-content/uploads/2022/08/2-2-768x637.png 768w" sizes="(max-width: 957px) 100vw, 957px" title="FinLab x Google雲端平台 | 3步驟實現全自動交易，從今以後躺著都能賺！(上) 33"></figure>



<p>登入後會有兩種可能的狀況：</p>



<ul><li>從未在這台電腦申請過交易憑證<ul><li>系統會跳視窗自動會引導你申請憑證，按照指引一步一步做即可</li></ul></li><li>先前在這台電腦申請過交易憑證，但不是最新版的<ul><li>先點選<strong>憑證註銷</strong>後，再重新申請憑證即可</li></ul></li></ul>



<h3>小提醒</h3>



<p>在申請憑證的過程中不要更動檔案路徑，申請完後你的憑證就會儲存在<strong>&#8220;C:\ekey\551\身分證字號\S&#8221;的資料夾中，資料夾中名為Sinopac的檔案就是之後要上傳到GCP的交易憑證。</strong></p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="287" src="https://www.finlab.tw/wp-content/uploads/2022/08/3-2-1024x287.png" alt="3 2" class="wp-image-4243" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/3-2-1024x287.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/08/3-2-300x84.png 300w, https://www.finlab.tw/wp-content/uploads/2022/08/3-2-768x215.png 768w, https://www.finlab.tw/wp-content/uploads/2022/08/3-2.png 1140w" sizes="(max-width: 1024px) 100vw, 1024px" title="FinLab x Google雲端平台 | 3步驟實現全自動交易，從今以後躺著都能賺！(上) 34"></figure>



<h2>永豐模擬測試 (2022/09/22 更新)</h2>



<p>永豐為配合主管機關，在9/20更新了政策，<strong>規定所有用戶必須2022/11/01前完成測試流程，否則將會停止客戶的API委託下單權限。</strong></p>



<p>因此請大家花幾分鐘，按照<a href="https://www.sinotrade.com.tw/ec/20191125/Docs/Python%20API%E6%B8%AC%E8%A9%A6%E6%B5%81%E7%A8%8B.pdf" target="_blank" rel="noreferrer noopener">永豐測試流程PDF</a>完成所有的測試流程，以免被停權喔！（只要做這一次即可）</p>



<p>永豐在PDF中有提供測試程式檔(圖中紅色箭頭處)，只要填入在程式檔中填入自己的帳號密碼後，按說明依序執行即可。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="576" src="https://www.finlab.tw/wp-content/uploads/2022/09/image-10-1024x576.png" alt="image 10" class="wp-image-4434" srcset="https://www.finlab.tw/wp-content/uploads/2022/09/image-10-1024x576.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/09/image-10-300x169.png 300w, https://www.finlab.tw/wp-content/uploads/2022/09/image-10-768x432.png 768w, https://www.finlab.tw/wp-content/uploads/2022/09/image-10-800x450.png 800w, https://www.finlab.tw/wp-content/uploads/2022/09/image-10.png 1192w" sizes="(max-width: 1024px) 100vw, 1024px" title="FinLab x Google雲端平台 | 3步驟實現全自動交易，從今以後躺著都能賺！(上) 35"><figcaption><strong>點選紅色箭頭處，即可取得測試用程式檔</strong></figcaption></figure>



<p>有幾點要注意的地方：</p>



<ol><li>shioaji套件須更新到 <strong>0.3.6.dev3</strong></li><li>只能在 <strong>2pm~6pm</strong> 之間進行模擬測試</li><li>確保<code>02_shioaji_sign_status.ipynb</code> 執行到最後時，執行<code>api.login()</code>後要看到<code>StockAccount</code>的<code>signed=True</code>才算是完成喔！</li></ol>



<h1>FinLab</h1>



<p>為了符合Cloud Function所規定的形式，接下來要將寫好的選股策略打包成函式，並加入FinLab串接下單的程式碼。</p>



<h2>撰寫策略</h2>



<p>首先要先有一隻策略佈署，這邊我使用<a href="https://doc.finlab.tw/tools/%E8%82%A1%E5%83%B9%E5%89%B5%E6%96%B0%E9%AB%98%E5%8B%95%E8%83%BD/" target="_blank" rel="noreferrer noopener">FinLab公開文檔</a>中的<strong>股價創新高動能策略</strong>作為示範。</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from finlab.backtest import sim
from finlab import data
close = data.get("price:收盤價")
position = (close == close.rolling(250).max())
report = sim(position, resample="M", name="創年新高策略")</code></pre>



<h2>將策略打包成函式</h2>



<p>若要上傳到策略到Clound Funciton，程式碼必須以函式的方式呈現。因此我將程式碼簡單打包如下，若對函式不熟悉的同學可以參考這篇<a href="https://yc-note.com/python/python-3/" target="_blank" rel="noreferrer noopener">文章</a>！</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from finlab.backtest import sim
from finlab import data

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</code></pre>



<h2>串接FinLab下單模組</h2>



<p>FinLab提供的下單模組，讓大家可以用策略回測的report物件來下單，更多的詳情請參考這份<a href="https://doc.finlab.tw/details/order_api/" target="_blank" rel="noreferrer noopener">官方文檔</a>，裡面有完整的介紹(附程式碼)。</p>



<p>以下是我撰寫的簡短範例code，預設將以10萬資金量來下市價委託單。</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from finlab.online.order_executor import Position
from finlab.online.sinopac_account import SinopacAccount
from finlab.online.order_executor import OrderExecutor
import os

def make_order(report,fund=100000): #預設用100,000的資金跑策略，市價下單
  os.environ['SHIOAJI_ACCOUNT']= '永豐證券帳號'
  os.environ['SHIOAJI_PASSWORD']= '永豐證券密碼'
  os.environ['SHIOAJI_CERT_PATH']= '永豐證券憑證路徑'
  os.environ['SHIOAJI_CERT_PASSWORD'] = '永豐證券憑證密碼' #預設與身份證同
  position = Position.from_report(report, fund)
  acc = SinopacAccount()
  order_executer = OrderExecutor(position , account=acc) 
  # 實際下單（會真的下單，初次使用建議收市時測試）
  order_executer.create_orders(market_order=True) #用市價單(要注意滑價，可自行修改)
  return</code></pre>



<h1>總結</h1>



<p>這篇文章我們完成了布置到GCP所需的前置作業，包括申請交易憑證、打包策略程式碼、加入下單模組，但目前的程式碼還無法實際應用。</p>



<p>在下篇<a href="https://www.finlab.tw/auto-trading-part2/" target="_blank" rel="noreferrer noopener">文章</a>中，我們會將這些東西進行細微的修改，以符合GCP的規定格式，並上傳到GCP以Cloud Function部署，最後用Cloud Scheduler定期呼叫Cloud Function就大功告成了！</p>



<p>今天的分享就到這裡結束了，我是阿榤，下次見，掰！(⁎⁍̴̛ᴗ⁍̴̛⁎)</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/auto-trading-part1/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4228</post-id>	</item>
	</channel>
</rss>
