自己做量化交易軟件(22)小白量化之MetaTrader5自動交易1

自己做量化交易軟件(22)小白量化之MetaTrader5自動交易1

小白量化框架源代碼是《零基礎搭建量化投資系統――以Python爲工具》的隨書演示代碼.
作者其中之一楊老師利用小白量化系統參加外匯期貨實戰比賽,取得了8天獲利860%的戰績.
在這裏插入圖片描述
我看了這個戰績,我從心裏羨慕、嫉妒、外加眼紅,讓楊老師把交易策略告訴我。通過學習,我進行實戰聯繫,獲得了1天獲利105%的成績。
在這裏插入圖片描述
很多讀者也希望瞭解小白量化系統在MetaTrader5回測及自動交易的應用,因此我寫這篇介紹給廣大朋友。本文只涉及電腦技術,不涉及交易策略。
1、首先是pip安裝MetaTrader5.如果讀者使用了本系列前篇的“綠色Py37”,需要如下操作,安裝必要庫。

python -m pip install --upgrade pip
pip install MetaTrader5
pip install numpy -U

2、《零基礎搭建量化投資系統――以Python爲工具》讀者羣複製小白量化2模塊到用戶新建目錄中。
3、安裝MetaTrader5軟件,安裝好後,申請DEMO用戶,開啓算法交易。
4、開始編寫MT5的Python程序

#引入相關庫
import MetaTrader5 as mt5
import HP_mt5 as hmt5

#初始化小白mt5庫
hmt5.init()

#登陸用戶mt5的帳戶
hmt5.login(login=用戶名, server=服務器名,password=用戶密碼)

#輸出mt5連接相關信息
hmt5.info()

#獲取用戶登陸信息
#accountinfo=mt5.account_info()
#print(accountinfo)

程序如果連接成功,會出現如下結果。

顯示有關MetaTrader 5程序包的數據
MetaTrader5 package author:  MetaQuotes Software Corp.
MetaTrader5 package version:  5.0.33
# 顯示有關連接狀態、服務器名稱和交易賬戶的數據
TerminalInfo(community_account=False, community_connection=False, connected=True, dlls_allowed=False, trade_allowed=True, tradeapi_disabled=False, email_enabled=False, ftp_enabled=False, notifications_enabled=False, mqid=False, build=2489, maxbars=100000, codepage=936, ping_last=222091, community_balance=0.0, retransmission=0.07995623448217817, company='True ECN Trading Ltd', name='MetaTrader 5 IC Markets (SC)', language='Chinese (Simplified)', path='C:\\Program Files\\MetaTrader 5 IC Markets (SC)', ...)
# 顯示有關MetaTrader 5版本的數據
(500, 2489, '12 Jun 2020')

5、現價開多單

hmt5.buy(symbol = "XAUUSD",volume=0.01)

6、現價開空單

hmt5.sell(symbol = "XAUUSD",volume=0.01)

7、平倉

hmt5.pingcang(id)

8、清倉,平倉掉所有獲利大於profit的所有單子

 hmt5.qingcang(profit=-9999999)

9、止贏,平倉掉所有獲利大於profit的所有單子

 hmt5.zhiying(profit=-9999999)

10、止損,平倉掉所有獲利小於profit的所有單子

 hmt5.zhisun(profit=-100)

11、MT5行情數據轉小白量化數據格式,hq爲MT5獲取的行情數據

 hmt5.tohpdata(hq)

12、獲取MT5的倉單,並返回DataFrame 對象格式.

 hmt5.reload_positions(symbol="XAUUSD")

介紹了相關小白量化的演示,下面給交易的例子。

#引入相關庫
import MetaTrader5 as mt5
import HP_mt5 as hmt5

#初始化小白mt5庫
hmt5.init()

#登陸用戶mt5的帳戶
#hmt5.login(login=用戶名, server=服務器名,password=用戶密碼)
hmt5.login(login=5019, server="ICMarkets-Demo",password="XBrX")

#輸出mt5連接相關信息
hmt5.info()

#獲取用戶登陸信息
#accountinfo=mt5.account_info()
#print(accountinfo)


hmt5.reload_positions()
hmt5.buy()
hmt5.buy()
hmt5.buy()
hmt5.buy()
hmt5.sell()
hmt5.sell()
hmt5.sell()
hmt5.sell()
hmt5.sell()

程序運行結果。

訂單數: 1
多單買入價: 1725.6
訂單數: 2
多單買入價: 1725.59
訂單數: 3
多單買入價: 1725.59
訂單數: 4
多單買入價: 1725.59
訂單數: 5
空單賣出價: 1725.23
訂單數: 6
空單賣出價: 1725.29
訂單數: 7
空單賣出價: 1725.63
訂單數: 8
空單賣出價: 1725.64
訂單數: 9
空單賣出價: 1725.66
訂單數: 10

在這裏插入圖片描述
這篇先介紹到這裏,有興趣的朋友,可以繼續看下一篇。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章