自己做量化交易软件(23)小白量化之MetaTrader5自动交易2

自己做量化交易软件(23)小白量化之MetaTrader5自动交易2
上一篇我们介绍了MetaTrader 5关于交易类的函数功能,这篇文章主要介绍行情获取等方面知识。
一、获取MetaTrader 5程序端中所有交易品种的数量。

import HP_mt5 as hmt5

# 建立与MetaTrader 5程序端的连接
if not hmt5.initialize():
    print("initialize() failed, error code =",hmt5.last_error())
    quit()
 
# 获取交易品种的数量
symbols=hmt5.symbols_total()
if symbols>0:
    print("Total symbols =",symbols)
else:
    print("symbols not found")
 
# 断开与MetaTrader 5程序端的连接
hmt5.shutdown()

运行结果:

Total symbols = 260

二、获取MetaTrader 5程序端中的所有交易品种。

import HP_mt5 as hmt5

# 建立与MetaTrader 5程序端的连接
if not hmt5.initialize():
    print("initialize() failed, error code =",hmt5.last_error())
    quit()
 
# 获取所有交易品种
symbols=hmt5.symbols_get()
print('Symbols: ', len(symbols))
count=0
# 显示前五个交易品种
for s in symbols:
    count+=1
    print("{}. {}".format(count,s.name))
    if count==5: break
print()
 
# 获取名称中包含RU的交易品种
ru_symbols=hmt5.symbols_get(group="*RU*")
print('len(*RU*): ', len(ru_symbols))
for s in ru_symbols:
    print(s.name)
print()
 
# 获取名称中不包含USD、EUR、JPY和GBP的交易品种
group_symbols=hmt5.symbols_get(group="*,!*USD*,!*EUR*,!*JPY*,!*GBP*")
print('len(*,!*USD*,!*EUR*,!*JPY*,!*GBP*):', len(group_symbols))
for s in group_symbols:
    print(s.name,":",s)
 
# 断开与MetaTrader 5程序端的连接
hmt5.shutdown()

运行结果:

Symbols:  260
1. EURUSD
2. GBPUSD
3. USDCHF
4. USDJPY
5. USDCAD

len(*RU*):  3
EURUSD
USDRUB
XBRUSD

。。。后面输出信息省略

三、获取指定交易品种的数据。

import HP_mt5 as hmt5

# 建立与MetaTrader 5程序端的连接
if not hmt5.initialize():
    print("initialize() failed, error code =",hmt5.last_error())
    quit()
 
# 尝试在市场报价中启用显示EURJPY交易品种
selected=hmt5.symbol_select("EURJPY",True)
if not selected:
    print("Failed to select EURJPY")
    hmt5.shutdown()
    quit()
 
# 显示EURJPY交易品种属性
symbol_info=hmt5.symbol_info("EURJPY")
if symbol_info!=None:
    # display the terminal data 'as is'    
    print(symbol_info)
    print("EURJPY: spread =",symbol_info.spread,"  digits =",symbol_info.digits)
    # display symbol properties as a list
    print("Show symbol_info(\"EURJPY\")._asdict():")
    symbol_info_dict = hmt5.symbol_info("EURJPY")._asdict()
    for prop in symbol_info_dict:
        print("  {}={}".format(prop, symbol_info_dict[prop]))
 
# 断开与MetaTrader 5程序端的连接
hmt5.shutdown()

运行结果:

SymbolInfo(custom=False, chart_mode=0, select=True, visible=True, session_deals=0, session_buy_orders=0, session_sell_orders=0, volume=0, volumehigh=0, volumelow=0, time=0, digits=3, spread=0, spread_float=True, ticks_bookdepth=10, trade_calc_mode=0, trade_mode=4, start_time=0, expiration_time=0, trade_stops_level=0, trade_freeze_level=0, trade_exemode=2, swap_mode=1, swap_rollover3days=3, margin_hedged_use_leg=False, expiration_mode=15, filling_mode=2, order_mode=127, order_gtc_mode=0, option_mode=0, ...)
EURJPY: spread = 0   digits = 3
Show symbol_info("EURJPY")._asdict():
  custom=False
  chart_mode=0
  select=True
  visible=True
  session_deals=0
  session_buy_orders=0
  session_sell_orders=0
  volume=0
  volumehigh=0
  volumelow=0
  time=0
  digits=3
  spread=0
  spread_float=True
  ticks_bookdepth=10
  trade_calc_mode=0
  trade_mode=4
  start_time=0
  expiration_time=0
  trade_stops_level=0
  trade_freeze_level=0
  trade_exemode=2
  swap_mode=1
  swap_rollover3days=3
  margin_hedged_use_leg=False
  expiration_mode=15
  filling_mode=2
  order_mode=127
  order_gtc_mode=0
  option_mode=0
  option_right=0
  bid=0.0
  bidhigh=0.0
  bidlow=0.0
  ask=0.0
  askhigh=0.0
  asklow=0.0
  last=0.0
  lasthigh=0.0
  lastlow=0.0
  volume_real=0.0
  volumehigh_real=0.0
  volumelow_real=0.0
  option_strike=0.0
  point=0.001
  trade_tick_value=0.935182500865044
  trade_tick_value_profit=0.935182500865044
  trade_tick_value_loss=0.935182500865044
  trade_tick_size=0.001
  trade_contract_size=100000.0
  trade_accrued_interest=0.0
  trade_face_value=0.0
  trade_liquidity_rate=0.0
  volume_min=0.01
  volume_max=100.0
  volume_step=0.01
  volume_limit=0.0
  swap_long=-3.74
  swap_short=-1.04
  margin_initial=100000.0
  margin_maintenance=0.0
  session_volume=0.0
  session_turnover=0.0
  session_interest=0.0
  session_buy_orders_volume=0.0
  session_sell_orders_volume=0.0
  session_open=0.0
  session_close=0.0
  session_aw=0.0
  session_price_settlement=0.0
  session_price_limit_min=0.0
  session_price_limit_max=0.0
  margin_hedged=0.0
  price_change=0.0
  price_volatility=0.0
  price_theoretical=0.0
  price_greeks_delta=0.0
  price_greeks_theta=0.0
  price_greeks_gamma=0.0
  price_greeks_vega=0.0
  price_greeks_rho=0.0
  price_greeks_omega=0.0
  price_sensitivity=0.0
  basis=
  category=
  currency_base=EUR
  currency_profit=JPY
  currency_margin=EUR
  bank=
  description=Euro vs Japanese Yen
  exchange=
  formula=
  isin=
  name=EURJPY
  page=
  path=Forex\Minors\EURJPY

四、获取行情数据及小白量化之仿通达信指标计算

import pandas as pd
from HP_formula import *
import MetaTrader5 as mt5
import HP_mt5 as hmt5

# 建立与MetaTrader 5程序端的连接
if not hmt5.initialize():
    print("initialize() failed, error code =",hmt5.last_error())
    quit()
 

'''
TIMEFRAME 是一个包含可能图表周期值的枚举
ID	         描述
TIMEFRAME_M1	1分钟
TIMEFRAME_M2	2 分钟
TIMEFRAME_M3	3 分钟
TIMEFRAME_M4	4 分钟
TIMEFRAME_M5	5 分钟
TIMEFRAME_M6	6 分钟
TIMEFRAME_M10	10 分钟
TIMEFRAME_M12	12 分钟
TIMEFRAME_M12	15 分钟
TIMEFRAME_M20	20 分钟
TIMEFRAME_M30	30 分钟
TIMEFRAME_H1	1 小时
TIMEFRAME_H2	2 小时
TIMEFRAME_H3	3 小时values
TIMEFRAME_H4	4 小时
TIMEFRAME_H6	6 小时
TIMEFRAME_H8	8 小时
TIMEFRAME_H12	12 小时
TIMEFRAME_D1	1 天
TIMEFRAME_W1	1 周
TIMEFRAME_MON1	1 个月
'''
# 在UTC时区,获取01.10.2020开始的10个EURUSD H4柱形图
rates = hmt5.copy_rates_from_pos("XAUUSD", mt5.TIMEFRAME_H1, 0, 2440)
df=hmt5.tohpdata(rates)
print(df)

#下面是小白仿通达信公式系统计算
#首先要对数据预处理
mydf=df.copy()
CLOSE=mydf['close']
LOW=mydf['low']
HIGH=mydf['high']
OPEN=mydf['open']
C=mydf['close']
L=mydf['low']
H=mydf['high']
O=mydf['open']


def RSI(N1=6, N2=12, N3=24):
    """
    RSI 相对强弱指标
    """
    LC = REF(CLOSE, 1)
    RSI1 = SMA(MAX(CLOSE - LC, 0), N1, 1) / SMA(ABS(CLOSE - LC), N1, 1) * 100
    RSI2 = SMA(MAX(CLOSE - LC, 0), N2, 1) / SMA(ABS(CLOSE - LC), N2, 1) * 100
    RSI3 = SMA(MAX(CLOSE - LC, 0), N3, 1) / SMA(ABS(CLOSE - LC), N3, 1) * 100

    return RSI1, RSI2, RSI3

#假定我们使用RSI指标
r1,r2,r3=RSI()

mydf = mydf.join(pd.Series( r1,name='RSI1'))  
mydf = mydf.join(pd.Series( r2,name='RSI2'))  
mydf = mydf.join(pd.Series( r3,name='RSI3')) 
mydf['S80']=80  #增加上轨80轨迹线
mydf['X20']=20  #增加下轨20轨迹线

mydf=mydf.tail(100)  #显示最后100条数据线 

#下面是绘线语句
mydf.S80.plot.line()
mydf.X20.plot.line()
mydf.RSI1.plot.line(legend=True)
mydf.RSI2.plot.line(legend=True)
mydf.RSI2.plot.line(legend=True)


# 断开与MetaTrader 5程序端的连接
hmt5.shutdown()

运行结果:

                    time     open     high      low    close  tick_volume  spread  real_volume                date
0    2020-01-21 01:00:00  1560.88  1561.49  1559.95  1561.27         1512       2            0 2020-01-21 01:00:00
1    2020-01-21 02:00:00  1561.27  1561.96  1560.36  1560.45         2179       2            0 2020-01-21 02:00:00
2    2020-01-21 03:00:00  1560.46  1567.94  1560.03  1566.67        10579       2            0 2020-01-21 03:00:00
3    2020-01-21 04:00:00  1566.67  1568.63  1564.60  1567.01         7646       2            0 2020-01-21 04:00:00
4    2020-01-21 05:00:00  1567.00  1567.31  1565.53  1566.86         4221       2            0 2020-01-21 05:00:00
5    2020-01-21 06:00:00  1566.87  1567.75  1566.28  1566.60         2179       2            0 2020-01-21 06:00:00

显示图形如下:
自己做量化交易软件(23)小白量化之MetaTrader5自动交易2_第1张图片
以上文章介绍了MetaTrader5的Python方面的程序开发。MetaTrader5提供了外汇,期货,数字币等行情数据。读者不难结合前面的文章,根据自己策略写出全自动交易程序。
独狼荷蒲qq:2886002
通通小白python量化群:524949939
微信公众号:独狼股票分析

你可能感兴趣的:(软件开发,python,量化软件,MetaTrader5,小白量化,GUI,荷蒲,比特币)