Ejemplo n.º 1
0
def get_symbols(group=None):
    """
    :param group: https://www.mql5.com/en/docs/integration/python_metatrader5/mt5symbolsget_py, refer to this website for usage of group
    :return: tuple(symbolInfo), there are several property
    """
    if group:
        symbols = mt5.symbols_get(group)
    else:
        symbols = mt5.symbols_get()
    return symbols
Ejemplo n.º 2
0
def historyData(Symbol):
    mt5.initialize(server="ForexClub-MT5 Demo Server",
                   login=500063649,
                   password="******")
    # print(mt5.terminal_info())
    # print(mt5.version())
    listSymbols = mt5.symbols_get()
    # [x.name for x in listSymbols]
    # Symbol=np.random.choice(FXmajor, 1)[0]
    print(Symbol)
    pointValue = mt5.symbol_info(Symbol).point
    # mt5.Buy("EURUSD", 0.1,price=11395,ticket=9)
    Num_velas = 1000
    # Copying data to pandas data frame
    # rates =  mt5.copy_rates_from_pos(Symbol, mt5.TIMEFRAME_M1, 0, Num_velas)
    rates = mt5.copy_rates_range(Symbol, mt5.TIMEFRAME_H1,
                                 datetime(2021, 1, 10), datetime.now())
    # rates =  mt5.copy_rates_range("ES", mt5.TIMEFRAME_D1, datetime(2019, 1, 15), datetime(2019, 1, 25))
    # rates =  mt5.copy_rates_from_pos(Symbol, mt5.TIMEFRAME_M1, 0, Num_velas)

    # Deinitializing MT5 connection
    mt5.shutdown()
    # create DataFrame out of the obtained data
    rates_frame = pd.DataFrame(rates)
    # convert time in seconds into the datetime format
    rates_frame.index = pd.to_datetime(rates_frame['time'], unit='s')

    rates_frame.columns = [
        'time', 'Open', 'High', 'Low', 'Close', 'tick_volume', 'spread',
        'real_volume'
    ]
    return rates_frame
Ejemplo n.º 3
0
    def get_symbols(self):
        """Get all financial instruments from the MetaTrader5 terminal.

        Returns:
            list: List of symbol names
        """
        symbols = mt5.symbols_get()
        result = [s.name for s in symbols]
        return result
Ejemplo n.º 4
0
    def run(self):
        c = dt.cur(True)
        for k, v in fn.required_tables.items():
            c.execute("DROP TABLE IF EXISTS " + k)
            c.execute("CREATE TABLE " + k + " " + v)

        sum_all = len(self.names)
        for s in range(
                sum_all):  # never change global statements inside a loop
            self.install_progress = (100 / sum_all) * s
            symbol_name = self.names[s]
            index = self.indices[symbol_name]
            print("Classifying symbol", s, "of", sum_all)

            # Find branch
            page = Classify.requests_retry_session() \
                .get("http://tsetmc.com/Loader.aspx?ParTree=151311&i=" + index, timeout=10).text
            branch = re.findall(r"LSecVal='([\D]*)',", page)
            if len(branch) == 0:
                print("UNKNOWN SYMBOL!!!", s)
                continue
            branch = branch[0]

            # TABLE branch
            c.execute("SELECT * FROM branch WHERE name='" + branch +
                      "' LIMIT 1")
            exists = list()
            for i in c:
                exists.append(i)
            if len(exists) == 0:
                c.execute("INSERT INTO branch (name) VALUES (?)", [branch])
                dt.connect.commit()
                branch_id = c.lastrowid
            else:
                branch_id = exists[0][0]

            # TABLE symbol
            got = mt5.symbols_get(symbol_name)
            if got is not None and len(got) > 0:
                inf = got[0].description
            else:
                inf = None  # if the Mofid server is off, this will be returned!!!
            c.execute(
                "INSERT INTO symbol (id, name, info, branch) VALUES (?, ?, ?, ?)",
                (index, symbol_name, inf, branch_id))
            dt.connect.commit()
        dt.cur(False)
        self.active = False
Ejemplo n.º 5
0
    def get_symbols(self):
        """
        Gets list of symbols open in MT5 market watch.
        :return: list of symbol names
        """
        # Iterate symbols and get those in market watch.
        symbols = MetaTrader5.symbols_get()
        selected_symbols = []
        for symbol in symbols:
            if symbol.visible:
                selected_symbols.append(symbol.name)

        # Log symbol counts
        total_symbols = MetaTrader5.symbols_total()
        num_selected_symbols = len(selected_symbols)
        self.__log.debug(
            f"{num_selected_symbols} of {total_symbols} available symbols in Market Watch."
        )

        return selected_symbols
Ejemplo n.º 6
0
def get_all_symbols_info():
    """
    :return: dict[symbol] = collections.nametuple
    """
    symbols_info = {}
    symbols = mt5.symbols_get()
    for symbol in symbols:
        symbol_name = symbol.name
        symbols_info[symbol_name] = collections.namedtuple(
            "info",
            ['digits', 'base', 'quote', 'swap_long', 'swap_short', 'pt_value'])
        symbols_info[symbol_name].digits = symbol.digits
        symbols_info[symbol_name].base = symbol.currency_base
        symbols_info[symbol_name].quote = symbol.currency_profit
        symbols_info[symbol_name].swap_long = symbol.swap_long
        symbols_info[symbol_name].swap_short = symbol.swap_short
        if symbol_name[3:] == 'JPY':
            symbols_info[
                symbol_name].pt_value = 100  # 100 dollar for quote per each point    (See note Stock Market - Knowledge - note 3)
        else:
            symbols_info[
                symbol_name].pt_value = 1  # 1 dollar for quote per each point  (See note Stock Market - Knowledge - note 3)
    return symbols_info
Ejemplo n.º 7
0
"""

import pandas as pd
from datetime import datetime
import time

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

import MetaTrader5 as mt5

if not mt5.initialize():
    print("fail do init")
    mt5.shutdown()
    
stocks = mt5.symbols_get()

def get_data(stock,timeframe, n=5):
    val = mt5.copy_rates_from_pos(stock, timeframe, 0 , 5)
    val = pd.DataFrame(val)
    val['time'] = pd.to_datetime(val['time'], unit= 's')
    val.set_index('time', inplace=True)
    return val

#print(get_data('USDJPY', mt5.TIMEFRAME_M1))

#plt.style.use('fivethirtyeight')
fig, ax = plt.subplots()
graph1, = ax.plot([],[], label = 'USDJPY')
ax.set_title('Classes')
ax.set_xlabel('time')
Ejemplo n.º 8
0
from datetime import datetime
import pandas as pd
import MetaTrader5 as mt5
import json

# connect to MetaTrader 5
if not mt5.initialize():
    print("initialize() failed")
    mt5.shutdown()

symbols = mt5.symbols_get()

print(json.dumps(symbols))
Ejemplo n.º 9
0
import MetaTrader5 as mt5
import pytz
from datetime import datetime, timezone
import pandas as pd

# メタトレーダにログイン
if not mt5.initialize("C:\\path\\to\\installed\\terminal64.exe",
                      login=99999999999,
                      server="Exness-MT5Trial2",
                      password="******"):
    print("ログイン失敗, error code =", mt5.last_error())
    exit(1)

# とりあえず取引可能な銘柄を5つほどピックアップ
symbols = mt5.symbols_get()
print('Symbols: ', len(symbols))
count = 0

for s in symbols:
    count += 1
    print("{}. {}".format(count, s.name))
    if count == 5: break

# BTCペアを表示してみる
btc_symbols = mt5.symbols_get("*BTC*")
print('len(*BTC*): ', len(btc_symbols))
for s in btc_symbols:
    print(s.name)

symbol = "BTCUSD"
tf = mt5.TIMEFRAME_M1
Ejemplo n.º 10
0
# Uncomment below if you want to see your account info
# account_info=mt5.account_info()
# print(account_info)

# Set up the time period (IMPORTANT)
timeDict = {
    '1': mt5.TIMEFRAME_M1,
    '15': mt5.TIMEFRAME_M15,
    '30': mt5.TIMEFRAME_M30,
    '60': mt5.TIMEFRAME_H1
}
timePeriod = '15'

# Get the data for n periods prior to the current period
numBefore = 40  # number of periods prior to the current one
signals = mt5.symbols_get(group="*GBP*,!*JPY*,!*EUR*")
signalNames = [sig.name for sig in signals]

# Set up the credentials for sending mail
port = 465  # For SSL
smtp_server = "smtp.gmail.com"
sender_email = "*****@*****.**"  # Enter your address
receiver_email = "*****@*****.**"  # Enter receiver address
password = '******'

##################################################################################
##################################################################################
##################################################################################
##################################################################################
### WANT TO DO THE NEXT CODE EVERY TIME PERIOD (i.e. WHENEVER THERE IS MORE DATA)
print('\n\n**************STARTING THE TRADING BOT NOW****************\n')
Ejemplo n.º 11
0
import MetaTrader5 as mt5
mt5.initialize()

simbolos = mt5.symbols_get()

for s in simbolos:
    if 'USD' in s.name:
        print(s.name)

mt5.shutdown()
Ejemplo n.º 12
0
# Uncomment below if you want to see your account info
# account_info=mt5.account_info()
# print(account_info)

# Set up the time period (IMPORTANT)
timeDict = {
    '1': mt5.TIMEFRAME_M1,
    '15': mt5.TIMEFRAME_M15,
    '30': mt5.TIMEFRAME_M30,
    '60': mt5.TIMEFRAME_H1
}
timePeriod = '60'

# Get the data for n periods prior to the current period
numBefore = 40  # number of periods prior to the current one
signals = mt5.symbols_get(
    group="*CAD*,!*HKD*,*CHF*,*EUR*,*JPY*,*GBP*,*AUD*,!*USDOLLAR*,*USD*")
signalNames = [sig.name for sig in signals]

# Set up the credentials for sending mail
port = 465  # For SSL
smtp_server = "smtp.gmail.com"
sender_email = "*****@*****.**"  # Enter your address
receiver_email = "*****@*****.**"  # Enter receiver address
password = '******'

##################################################################################
##################################################################################
##################################################################################
##################################################################################
### WANT TO DO THE NEXT CODE EVERY TIME PERIOD (i.e. WHENEVER THERE IS MORE DATA)
print('\n\n**************STARTING THE TRADING BOT NOW****************\n')
Ejemplo n.º 13
0
import MetaTrader5 as mt5

# 显示有关MetaTrader 5程序包的数据
print("MetaTrader5 package author: ", mt5.__author__)
print("MetaTrader5 package version: ", mt5.__version__)

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

# 获取所有交易品种
symbols = mt5.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 = mt5.symbols_get("*RU*")
print('len(*RU*): ', len(ru_symbols))
for s in ru_symbols:
    print(s.name)
print()

# 获取名称中不包含USD、EUR、JPY和GBP的交易品种
group_symbols = mt5.symbols_get(group="*,!*USD*,!*EUR*,!*JPY*,!*GBP*")
Ejemplo n.º 14
0
            trade = ca.Position(position)
            class_exposure += trade.adjusted_exposure()

    return abs(class_exposure)


#________Making asset class lists________#
forexList = list()
commoditiesList = list()
indexList = list()
bondsList = list()
equitiesList = list()
etfList = list()

#Getting all symbols in the terminal
allInfo = mt5.symbols_get()

#Segrigating symbols w.r.t their asset-class
for info in allInfo:
    if 'Forex' in info.path:
        forexList.append(info.name)
    elif 'Commodities' in info.path:
        commoditiesList.append(info.name)
    elif 'Indices' in info.path:
        indexList.append(info.name)
    elif 'Bonds' in info.path:
        bondsList.append(info.name)
    elif 'ETF' in info.path:
        etfList.append(info.name)
    elif 'Stock' in info.path:
        equitiesList.append(info.name)
Ejemplo n.º 15
0
print(f"module version: {mt5.__version__}")
print(f"Terminal Version: {mt5.version()}")

#____________________________________________________________#
# pass the strings below in .symbols_get() to extract symbols
# of specific asset classes into asset_list

usd_quote = "*USD"
usd_base = """USD*,!X*, !BTC*, !BCH*,!DSH*,
                !DSH*, !ETH*, !LTC*, !EOS*, !EMC*, !NMC*, !PPC*"""
commodities = "X*, !*.NYSE"
stock_nasdaq = "*.NAS"
stock_nyse = "*.NYSE"
Future = '*_*'
bonds = 'EURB*, EURSCHA*, ITBT*, JGB*, UKGB*, UST*, !USTEC'

all_ass_data = mt5.symbols_get()  # will return symbols of all tradable assets.
asset_list = list()

for info in all_ass_data:
    if info.custom == True:
        continue
    else:
        # print(info.name)
        asset_list.append(info.name)

print(asset_list)
# for i in asset_list:
#     print(i)
# mt5.shutdown()
#___Initialize MT5___#
mt5.initialize()


#________Creating denomination dictionary_________#
def pair_generator(symbol):
    """Takes the asset name and gives the USD converting forex pair
        ie. for AUD it will return AUDUSD"""

    if symbol in ['EUR', 'GBP', 'AUD', 'NZD']:
        return f'{symbol}USD'
    else:
        return f'USD{symbol}'


allinfo = mt5.symbols_get()

templist = list()
for info in allinfo:
    if info.currency_profit == 'USD' or info.currency_margin == 'USD':
        continue
    else:
        templist.append((info.name, info.currency_profit))

denoDict = dict()
for i in templist:
    denoDict[i[0]] = pair_generator(i[1])


#_________Swap calculating functions__________#
def fxAdjust(exposure, pair):
Ejemplo n.º 17
0
 def get_all_symbols(self):
     self.symbols = [s.name for s in mt5.symbols_get()]
     self.symbols_combobox["values"] = self.symbols
     self.symbols_combobox.current(0)
Ejemplo n.º 18
0
# All stocks trading < $100
import MetaTrader5 as mt5
import pandas as pd

mt5.initialize()

all_assets = mt5.symbols_get()

stocks = list()
small = list()

for asset in all_assets:
    if "Stock" in asset.path:
        stocks.append(asset.name)

for stock in stocks:
    if 'ETF' in mt5.symbol_info(stock).path:
        stocks.remove(stock)
# print(stocks)

for stock in stocks:
    mt5.symbol_select(stock)
    if mt5.symbol_info_tick(stock).ask <= 100:
        small.append(stock)

print(small)
print(len(small))
mt5.shutdown()
Ejemplo n.º 19
0
                return inputs.transpose(1, 0, 2, 3)

            return inputs
        else:
            raise StopIteration


# example
if __name__ == '__main__':
    from datetime import datetime
    import pytz
    if not mt5.initialize():
        print("initialize() failed")
        mt5.shutdown()

    symbol = [i.name for i in mt5.symbols_get()][:3]
    timezone = pytz.timezone("Etc/UTC")
    time1 = datetime(2021, 1, 27, 15, tzinfo=timezone)
    time2 = datetime(2021, 1, 28, 15, tzinfo=timezone)
    count = 10
    timeframe = mt5.TIMEFRAME_M30

    demo_set = MT5Dataset()
    demo_set.copy(symbol, time1, time2, timeframe=timeframe)
    demo_set.standard()
    print('data[:2, 0] : \n', demo_set.data[:2, 0])
    print('shape of data (count, symbols, columns) : ', demo_set.data.shape)

# class a():
#     def __init__(self):
#         self.data = torch.randint(0, 10, [11,7,5])
Ejemplo n.º 20
0
# Uncomment below if you want to see your account info

# account_info=mt5.account_info()
# print(account_info)

# Set up the time period (IMPORTANT)
timeDict = {
    '15': mt5.TIMEFRAME_M15,
    '30': mt5.TIMEFRAME_M30,
    '60': mt5.TIMEFRAME_H1
}
timePeriod = '15'

# Get the data for n periods prior to the current period
numBefore = 40  # number of periods prior to the current one
signals = mt5.symbols_get(
    group="*USD*,*EUR*,*JPY*,*GBP*,*AUD*,!*USDOLLAR*,!*TRY*")

# Set up the credentials for sending mail
port = 465  # For SSL
smtp_server = "smtp.gmail.com"
sender_email = "*****@*****.**"  # Enter your address
receiver_email = "*****@*****.**"  # Enter receiver address
password = '******'

# timezone = pytz.timezone("Etc/GMT+3")
timezone = pytz.timezone("Etc/GMT-3")
local_timezone = tzlocal.get_localzone()  # get pytz timezone

### WANT TO DO THE NEXT CODE EVERY TIME PERIOD (i.e. WHENEVER THERE IS MORE DATA)
print('\n\n**************STARTING THE TRADING BOT NOW****************\n\n')
Ejemplo n.º 21
0
etf = [
    'DBA.NYSE', 'EEM.NYSE', 'EWH.NYSE', 'EWW.NYSE', 'EWZ.NYSE', 'FXI.NYSE',
    'GDX.NYSE', 'GDXJ.NYSE', 'IEMG.NYSE', 'LQD.NYSE', 'MJ.NYSE', 'MOO.NYSE',
    'RSX.NYSE', 'SIL.NYSE', 'UNG.NYSE', 'URA.NYSE', 'USO.NYSE', 'VXX.NYSE',
    'VXXB.NYSE', 'VYM.NYSE', 'XLE.NYSE', 'XLF.NYSE', 'XLI.NYSE', 'XLP.NYSE',
    'XLU.NYSE', 'XOP.NYSE', 'QQQ.NAS', 'TLT.NAS'
]

#____________Variable Assets______________#
"""Assets that can change name periodically.
    Futures contracts change their names monthly"""

Future = '*_*, !Sugar*, !Corn*, !Coffee*, !Cocoa*, !Cotton*, !Wheat*, !OJ*, !Soyb*'

variable_assets = list()
all_ass_data = mt5.symbols_get(Future)

for info in all_ass_data:
    variable_assets.append(info.name)

variable_assets.sort()


def insertion(symbol):
    mt5.symbol_select(symbol)


def ask(assetName):
    info = mt5.symbol_info_tick(assetName)
    if info is None:
        insertion(assetName)
Ejemplo n.º 22
0
print(f"Terminal Build: {mt5.terminal_info().build}\n")


#__________________Creating Denomination Dictionary_____________________#
def pair_generator(symbol):  # symbol: Profit currency.
    """Takes the currency symbol and returns the USD converting forex pair,
        ie. for AUD it will return AUDUSD & USDJPY for JPY, etc."""

    if symbol in ['EUR', 'GBP', 'AUD', 'NZD']:
        return f'{symbol}USD'
    else:
        return f'USD{symbol}'


#_______________creating list1(line-24) automatically__________________#
allinfo = mt5.symbols_get()

templist = list()
for info in allinfo:
    if info.currency_profit == 'USD' or info.currency_margin == 'USD':
        continue
    else:
        templist.append((info.name, info.currency_profit))

list1 = dict()
for i in templist:
    list1[i[0]] = pair_generator(i[1])


#______________________Account class______________________#
class Account():
Ejemplo n.º 23
0
# account_info=mt5.account_info()
# print(account_info)

# Set up the time period (IMPORTANT)
timeDict = {
    '1': mt5.TIMEFRAME_M1,
    '15': mt5.TIMEFRAME_M15,
    '30': mt5.TIMEFRAME_M30,
    '60': mt5.TIMEFRAME_H1
}
timePeriod = '15'

# Get the data for n periods prior to the current period
numBefore = 40  # number of periods prior to the current one
signals = mt5.symbols_get(
    group=
    "*CAD*,*HKD*,*CHF*,*EUR*,*JPY*,*GBP*,*AUD*,!*USDOLLAR*,!*TRY*, !*SEK*, !*PLN*, !*DKK*, !*HUF*"
)
signalNames = [sig.name for sig in signals]

# Set up the credentials for sending mail
port = 465  # For SSL
smtp_server = "smtp.gmail.com"
sender_email = "*****@*****.**"  # Enter your address
receiver_email = "*****@*****.**"  # Enter receiver address
password = '******'

from dateutil import tz
HERE = tz.tzlocal()
UTC = tz.gettz('UTC+3')

### WANT TO DO THE NEXT CODE EVERY TIME PERIOD (i.e. WHENEVER THERE IS MORE DATA)