Example #1
0
def main():
    Mt5.initialize()
    Mt5.login(settings.METATRADE.LOGIN,
              password=settings.METATRADE.PASSWORD,
              server=settings.METATRADE.SERVER)
    for currency in models.Currency.objects.all().iterator(
    ):  # type: models.Currency
        print(currency)
        name = f"{currency.first}{currency.second}".upper()
        latest = models.Bar.objects.filter(
            currency=currency).latest("time_marker__time_marker")
        latest_datetime = datetime.combine(latest.time_marker.time_marker,
                                           datetime.min.time())
        date_to = datetime.utcnow() - timedelta(days=1)
        items = Mt5.copy_rates_range(name, Mt5.TIMEFRAME_D1, latest_datetime,
                                     date_to)
        if items is None:
            continue
        for item in items:
            close = item["close"]
            high = item["high"]
            low = item["low"]
            t = datetime.utcfromtimestamp(item["time"]).date()
            if t.weekday() in {6, 5}:
                continue
            time_marker = TimeMarker.objects.get_or_create(time_marker=t)[0]
            print(currency, time_marker)
            Bar.objects.update_or_create(currency=currency,
                                         time_marker=time_marker,
                                         defaults={
                                             "close": close,
                                             "high": high,
                                             "low": low
                                         })
Example #2
0
def main():
    Mt5.initialize()
    Mt5.login(settings.METATRADE.LOGIN, password=settings.METATRADE.PASSWORD, server=settings.METATRADE.SERVER)

    for deal in models.Deal.objects.filter(status__id=1, first__time_marker__time_marker=datetime(2020, 8, 20)):  # type: models.Deal
        result = deal.first
        if result.is_open():
            deal.close_first()

    for result in first_models.Result.objects.filter(status__id=1,
                                                     first__time_marker__time_marker=datetime(2020, 8, 20)):  # type: first_models.Result
        if models.Deal.objects.filter(result=result).exist():
            continue
        order = result.order
        if order.time_marker == result.time_marker:
            models.Deal.open_first(result=result)
Example #3
0
    def login(self):
        if not mt5.initialize():
            print("initialize() failed, error code =", mt5.last_error())
            quit()
        authorized = mt5.login(self.account, password=self.password)

        if not authorized:
            print("failed to connect at account #{}, error code: {}".format(
                self.account, mt5.last_error()))
Example #4
0
 def Initialization(account, password, timeout):
     mt5.initialize()
     # Connection with mt5 via socket
     authorized = mt5.login(account, password, timeout=timeout)
     if authorized == True:
         print("Initialization Finished")
     if authorized == False:
         print("Initialization Failed: Here is the error code:",
               mt5.last_error())
     return True
Example #5
0
def connect(account):
    account = int(account)
    mt5.initialize()
    authorized = mt5.login(account)

    if authorized:
        print("Connected: Connecting to MT5 Client")
    else:
        print("Failed to connect at account #{}, error code: {}".format(
            account, mt5.last_error()))
Example #6
0
    def connect(self):
        account = int(self.account_id)
        mt5.initialize()

        try:
            self.authorized = mt5.login(self.account_id)
        except not self.authorized:
            print(
                f"Failed to connect at account #{account}, error code: {mt5.last_error()}"
            )
Example #7
0
File: bot.py Project: slape/python
def connect_account(account):
    """Login to MetaTrader5 account using API."""
    account = int(account)
    mt5.initialize()
    authorized = mt5.login(account)
    if authorized:
        print('Connected: Connecting to MT5 Client')
    else:
        print(
            'Failed to connect at account #{}, error code: {}'.format(
                account, mt5.last_error(),
            ),
        )
Example #8
0
    def login(self):
        print(Fore.BLUE+'\nlogging in...')
        if mt5.login(self.acc_no,password = self.password,server = self.default_server):
            print(Fore.GREEN+'logged in successfully into acc:',self.acc_no,'on server:',self.default_server)
            print(Style.RESET_ALL)  
            print(Back.GREEN+'ACCOUNT INFORMATION') 
            print(Style.RESET_ALL)
  
            for k,v in mt5.account_info()._asdict().items():
                print('{:>50}'.format(k),v)

        else:print(Fore.RED+'log in failure with error:', mt5.last_error())
        print('\n')
Example #9
0
    def connect(self, account_id: int):
        """connect to the specific MT5 account

        Args:
            account_id (int):the MT5 account you want to connect to
        """
        mt5.initialize()
        authorized = mt5.login(account_id)

        if authorized:
            print("Connected: Connecting to MT5 Client")
        else:
            print("Failed to connect at account #{}, error code: {}".format(
                account_id, mt5.last_error()))
Example #10
0
 def Login(self):
     if not mt5.initialize(login=self.username, server=self.server, password=self.password):
         print("initialize() failed, error code =", mt5.last_error())
         quit()
     authorized = mt5.login(self.username, password=self.password)
     if authorized:
         account_info = mt5.account_info()
         if account_info != None:
             # convert the dictionary into DataFrame and print
             account_info_dict = mt5.account_info()._asdict()
             df=pd.DataFrame(list(account_info_dict.items()), columns=['property','value'])
             print(df)
     else:
         print("Failed to connect to trade account 25115284 with password=gqz0343lbdm, error code =", mt5.last_error()) 
         quit()
Example #11
0
    def login(self):
        # display data on the MetaTrader 5 package
        #print("MetaTrader5 package author: ", mt5.__author__)
        #print("MetaTrader5 package version: ", mt5.__version__)
        # establish connection to the MetaTrader 5 terminal
        if not mt5.initialize(self.PATH):
            print("initialize() failed, error code =", mt5.last_error())
            quit()

        authorized = mt5.login(self.login_id, password=self.password)
        if not authorized:
            print('LOGIN FAILED!!!')
            mt5.shutdown()
            quit()
        else:
            print("Login with account: ", str(self.login_id), " successfull!")
Example #12
0
# 建立与MetaTrader 5程序端的连接
if not mt5.initialize():
    print("initialize() failed, error code =",mt5.last_error())
    quit()

symbol = "USDJPY"

account = 64232831
# 4941427
account_password = "******"
account_server1= "XMGlobal-MT5"
account_server2= "XMGlobal-MT5 2"

server_url = "http://192.168.1.117:8081/"

mt5.login(account, server=account_server2, password=account_password)
# 检查是否存在活动订单

point = mt5.symbol_info(symbol).point
price = mt5.symbol_info_tick(symbol).ask + 1
deviation = 20

print("account info ",mt5.account_info())


# deal order
# request_deal = {
#     "action": mt5.TRADE_ACTION_DEAL,
#     "symbol": symbol,
#     "volume": 0.01,
#     "type": mt5.ORDER_TYPE_BUY,
Example #13
0
        'time']  # Just need the most recent time on the M1 timeframe
    return currTime


##################################################################################
##################################################################################
##################################################################################
##################################################################################
### INITIALISE EVERYTHING

## Initialise the MT5 trading portal
if not mt5.initialize():
    print(mt5.last_error())
    mt5.shutdown()
else:
    authorized = mt5.login(18676, password="******")

# 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
Example #14
0
import MetaTrader5 as mt5

if not mt5.initialize():
     print("initialize() failed, error code =",mt5.last_error())
     quit()

account=123456 #this is the login
password="******" # password to be entered
authorize_login = mt5.login(account,password)
if authorize_login:
     print(mt5.account_info())
     print("Show account_info()")
     account_info_dict=mt5.account_info()._asdict()
     for prop in account_info_dict:
          print("   {}={}".format(prop,account_info_dict[prop]))
else:
     print("failed to connect at account #{}, error code: {}".format(account, mt5.last_error()))

mt5.shutdown()
Example #15
0
mt5.initialize()                    #Connecting the program to MT5
print(mt5.version(), '\n')          #Version info of MT5 software

#___________Creating a terminal info dictionary____________#
trm_dict = mt5.terminal_info()._asdict()        #status info of the MT5 terminal
for i in trm_dict:
    print("{0}: {1}".format(i, trm_dict[i]))

#____________Creating an account info dictionary____________#
account_dict = mt5.account_info()._asdict()     #various information of the loggedin account
for i in account_dict:
    print(i, ':', account_dict[i])

#_______________puttng info in a pandas DataFrame_______________#
account_df = pd.DataFrame(list(account_dict.items()), columns=['property', 'value'])
trm_df = pd.DataFrame(list(trm_dict.items()), columns=['property', 'value'])

#_________________Brokerage account Login example_________________________#
'''SYNTAX: mt5.login(loginID, server='server_name', password='******')'''

loginID = 14000510
authentication = mt5.login(loginID, server='MetaQuotes-Demo', password='******')

if authentication:
    print(mt5.account_info())
else:
    print("failed to login to trade account {0}".format(loginID))


print(mt5.last_error())             #Returns error if any
mt5.shutdown()                      #break connection with MT5 Terminal
Example #16
0
# display data on the MetaTrader 5 package
print("MetaTrader5 package author: ", mt5.__author__)
print("MetaTrader5 package version: ", mt5.__version__)

# establish connection to the MetaTrader 5 terminal
if not mt5.initialize():
    print("initialize() failed, error code =", mt5.last_error())
    quit()

# display data on MetaTrader 5 version
print(mt5.version())
# connect to the trade account without specifying a password and a server
account = 17221085
authorized = mt5.login(
    account
)  # the terminal database password is applied if connection data is set to be remembered
if authorized:
    print("connected to account #{}".format(account))
else:
    print("failed to connect at account #{}, error code: {}".format(
        account, mt5.last_error()))

# now connect to another trading account specifying the password
account = 25115284
authorized = mt5.login(account, password="******")
if authorized:
    # display trading account data 'as is'
    print(mt5.account_info())
    # display trading account data in the form of a list
    print("Show account_info()._asdict():")
Example #17
0
from datetime import datetime
import matplotlib.pyplot as plt
import pandas as pd
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
import MetaTrader5 as mt5
 
account=40513145
authorized=mt5.login(account, password="******")  

# connect to MetaTrader 5
if not mt5.initialize():
    mt5.initialize()

  
 
# request connection status and parameters
print(mt5.terminal_info())
# get data on MetaTrader 5 version
print(mt5.version())
 
start_date=datetime(2021,1,27,10)
end_date=datetime(2021,1,27,11)

# request 1000 ticks from EURAUD
#datetime(year,month,day,hour)
euraud_ticks = mt5.copy_ticks_from("EURAUD", start_date, 1000, mt5.COPY_TICKS_ALL)
# request ticks from AUDUSD within 2019.04.01 13:00 - 2019.04.02 13:00
audusd_ticks = mt5.copy_ticks_range("AUDUSD", start_date, end_date, mt5.COPY_TICKS_ALL)
 
# get bars from different symbols in a number of ways
Example #18
0
            print(f'{recVals}\n')
            sendEmail(
                f'Subject: Make a trade on signal {currSig.name}\n\nHi there,\n\nCoding bot has found a suitable trade:\n\n{recVals}\n\nThanks'
            )

    return maxTime


## Initialise the MT5 trading portal
initTime = time.time()

if not mt5.initialize():
    print(mt5.last_error())
    mt5.shutdown()
else:
    authorized = mt5.login(62986, password="******")
    # print('\nInitialised mt5 successfully! Took %0.3f seconds...\n' % (time.time() - initTime))

# 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'
Example #19
0
 def login(self, account, server, password):
     print("当前登录的账号 = ", account)
     account = mt5.login(account, server=server, password=password)
     self._account_info = mt5.account_info()
     print("当前登录的账号信息  = ", self._account_info)
Example #20
0
from datetime import date
import pandas as pd
import matplotlib.pyplot as plt

import MetaTrader5 as mt5
# display data on the MetaTrader 5 package
print("MetaTrader5 package author: ", mt5.__author__)
print("MetaTrader5 package version: ", mt5.__version__)

# establish connection to the MetaTrader 5 terminal
if not mt5.initialize():
    print("initialize() failed, error code =", mt5.last_error())
    quit()

# now connect to another trading account specifying the password
account = 35146240
authorized = mt5.login(account, password="******")
if authorized:
    # display trading account data 'as is'
    print(mt5.account_info())
    """ # display trading account data in the form of a list
    print("Show account_info()._asdict():")
    account_info_dict = mt5.account_info()._asdict()
    for prop in account_info_dict:
        print("  {}={}".format(prop, account_info_dict[prop])) """
else:
    print("failed to connect at account #{}, error code: {}".format(
        account, mt5.last_error()))

# shut down connection to the MetaTrader 5 terminal
#mt5.shutdown()
Example #21
0
class malgo:

    try:
        if mt.initialize() == "true":
            print("Initialized!")
        else:
            mt.initialize()
    except Exception as e:
        print(e)

    try:
        if mt.login(login=26754957,
                    password="******",
                    server="MetaQuotes-Demo") == "true":
            print("loged in")
        else:
            mt.login(login=26754957,
                     password="******",
                     server="MetaQuotes-Demo")
    except Exception as e:
        print(e)

    def __init__(self):
        __account, __open_positon = mt.account_info(), mt.positions_get()
        """leverage = __account[2]
        balance = __account[10]
        limit_orders = __account[3]
        equity = __account[13]
        margin = __account[14]
        margin_free = __account[15]"""
        profit = __account[12]
        margin_level = round(__account[16], 2)
        name = __account[24]
        if len(__open_positon) > 0:
            exchange_rate = __open_positon[0][10]
            new_exchange_rate = __open_positon[0][13]
            symbol = __open_positon[0][16]

        try:
            if len(__open_positon) > 0:
                self.get_malgo(name, margin_level, profit, exchange_rate,
                               new_exchange_rate, symbol)
                self.get_ticks()

            else:
                self.get_ticks()
        except Exception as e:
            print(e)

    def get_ticks(self):
        eur_usd_tick, usd_jpy_tick = mt.symbol_info_tick(
            "EURUSD"), mt.symbol_info_tick("USDJPY")
        eur_usd_time = self.get_local_time(eur_usd_tick[0])
        usd_jpy_time = self.get_local_time(usd_jpy_tick[0])
        eur_usd = {
            "bid": eur_usd_tick[1],
            "ask": eur_usd_tick[2],
            "LT": eur_usd_time
        }
        usd_jpy = {
            "bid": usd_jpy_tick[1],
            "ask": usd_jpy_tick[2],
            "LT": usd_jpy_time
        }

        self.trades = {"EURUSD": eur_usd, "USDJPY": usd_jpy}

    def get_malgo(self, name, margin_level, profit, exchange_rate,
                  new_exchange_rate, symbol):

        #volume = __open_positon[0][9]
        #swap = __open_positon[0][14]
        #stop_loss = __open_positon[0][11]
        #stop_loss = __open_positon[0][12]

        select_time = self.get_local_time(mt.symbol_info_tick("EURUSD")[0])

        self.trade_positions = [{
            "Account Name": name,
            "Margin Level": round(margin_level, 2),
            "Symbol": symbol,
            "exchnage rate": exchange_rate,
            "Current Exchange Rate": new_exchange_rate,
            "Profit": profit,
            "Local Time": select_time
        }]

    def get_local_time(self, raw_time):
        raw_time = time.ctime(raw_time)
        date_time = datetime.strptime(raw_time, '%a %b %d %H:%M:%S %Y')
        local_date_time = date_time - timedelta(hours=3)
        local_date_time_string = local_date_time.strftime(
            '%a %b %d %H:%M:%S %Y')

        return local_date_time_string
Example #22
0
import MetaTrader5 as mt5
from datetime import datetime
import pandas as pd
import numpy as np

symbol = 'EURUSD'
# set up connection
mt5.initialize()
mt5.login(login=35146240, password="******")

positions = mt5.positions_get(symbol=symbol)

print(positions)
print(positions == None)

x = ()
Example #23
0
        print('connected to', self.addr)
        self.cummdata = ''
        while True:
            data = self.conn.recv(10000)
            self.cummdata += data.decode("utf-8")
            if not data:
                break
            self.conn.send(bytes(calcregr(self.cummdata), "utf-8"))
            return self.cummdata

    def __del__(self):
        self.sock.close()


# Connecting to Trade Account, Throwing an error code if failed
authorized = mt5.login(accout_number, password="******")
if authorized:
    print(mt5.account_info())  # Trading Account Data
else:
    print("Failed to connect to trade account, error code=", mt5.last_error)

print(mt5.terminal_info())
print(mt5.version())

now = datetime.now(
)  # Now specifically for the purpose of getting the data and placing the trades right now

gbpusd_ticks = mt5.copy_ticks_from("GBPUSD", now, 1, mt5.COPY_TICKS_ALL)
eurusd_ticks = mt5.copy_ticks_from("EURUSD", now, 1, mt5.COPY_TICKS_ALL)
audusd_ticks = mt5.copy_ticks_from("AUDUSD", now, 1, mt5.COPY_TICKS_ALL)
usdjpy_ticks = mt5.copy_ticks_from("USDJPY", now, 1, mt5.COPY_TICKS_ALL)
Example #24
0
import MetaTrader5 as mt5
import pandas as pd

# display data on the MetaTrader 5 package
print("MetaTrader5 package author: ", mt5.__author__)
print("MetaTrader5 package version: ", mt5.__version__)

# establish connection to the MetaTrader 5 terminal
if not mt5.initialize():
    print("initialize() failed, error code =", mt5.last_error())
    quit()

# connect to the trade account specifying a password and a server
authorized = mt5.login(38143049, server="MetaQuotes-Demo", password="******")
if authorized:
    account_info = mt5.account_info()
    if account_info != None:
        # display trading account data 'as is'
        print(account_info)
        # display trading account data in the form of a dictionary
        print("Show account_info()._asdict():")
        account_info_dict = mt5.account_info()._asdict()
        for prop in account_info_dict:
            print("  {}={}".format(prop, account_info_dict[prop]))
        print()

        # convert the dictionary into DataFrame and print
        df = pd.DataFrame(list(account_info_dict.items()),
                          columns=['property', 'value'])
        print("account_info() as dataframe:")
        print(df)
Example #25
0
import numpy as np
import pandas as pd
from datetime import datetime as dt
import numba as nb
from collections import defaultdict
from tqdm import tqdm

print('imported')

#%% Initialise the terminal etc

if not mt5.initialize():
    print(mt5.last_error())
    mt5.shutdown()
else:
    authorized = mt5.login(18676, password="******", server="GoMarkets-Demo")


def getData(numBefore, timePeriod, signal, timeDict):
    rates = mt5.copy_rates_from_pos(signal, timeDict[timePeriod], 0, numBefore)
    ratesDf = pd.DataFrame(rates)
    #    print(mt5.last_error())
    return ratesDf


# Give closePrices as an array
def getBollBands(closePrices, period=20, numStd=2):
    # Default values for bollinger bands = 20 for period & 2 for std
    bands = {k: []
             for k in ['topBand', 'bottomBand', 'mav']
             }  # Set lists as defaults
Example #26
0
import pandas as pd
import grafico as graf
import metodos_v4 as met
import timer as tm

# Connection with MetaTrader 5 terminal
if not mt5.initialize():
    print("initialize() failed, error code =", mt5.last_error())
    quit()

# Data on MetaTrader 5 version
print(mt5.version())

# User informations
account = "********"
authorized = mt5.login(account, password="******")

if not authorized:
    print("failed to connect at account #{}, error code: {}".format(
        account, mt5.last_error()))

# Establish a plot routine with Matplotlib
plt.ion()

# Setting initial code informations
time_range = 100
key = 0
curve = 0
fibo_list = []
valor_inicial = 0
tempos = []
Example #27
0
import numpy as np
from finta import TA
import MetaTrader5 as mt5
import pytz
from datetime import datetime, date

#  inserir seus dados
user = '******'
pwd = 'sua senha'
server = 'o servidor da sua corretora'

print('Conectando ao MetaTrader...')
# conecte-se ao MetaTrader 5
mt5.initialize()

authorized = mt5.login(login=user, password=pwd, server=server)
if authorized:
    # exibimos os dados sobre a conta de negociação como estão
    print('mt5.account_info()')
else:
    print("failed to connect at account #{}, error code: {}".format(
        user, mt5.last_error()))
    mt5.shutdown()

# impotação base com os ativos a ser analisados
ativos = pd.read_csv('E:\\Projects\\Bot_MetaTrader5-MT5\\data\\ativos.txt')
ativos = list(ativos['ativo'])

# criação de dataframe em branco
resposta = pd.DataFrame(columns=['Data', 'Ativo', 'Price', 'Método'])
Example #28
0
import MetaTrader5 as mt5
import random
import FinalCode.Orders as Orders

account = 820585
password = "******"

if not mt5.initialize():
    print(mt5.last_error())
    raise ValueError("Error! Did not initialise")
if not mt5.login(account, password=password):
    print(mt5.last_error())
    raise ValueError("Error! Did not login")

symbols = {"EURGBP": [], "GBPUSD": [], "EURUSD": []}

mt5.symbol_select("EURGBP", True)
mt5.symbol_select("GBPUSD", True)
mt5.symbol_select("EURUSD", True)


def algorithm():
    return {
        "EURGBP": [random.randint(2), [True, False][random.randint(2)]],
        "GBPUSD": [random.randint(2), [True, False][random.randint(2)]],
        "EURUSD": [random.randint(2), [True, False][random.randint(2)]]
    }


items = algorithm()
for symbol in items:
consumer_secret = "consumer_secret"
access_key = "access_key"
access_secret = "access_secret"

# Pass twitter credentials to tweepy via its OAuthHandler
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)

# connect to the trade account without specifying a password and a server
mt5.initialize()

# account number in the top left corner of the MT5 terminal window
# the terminal database password is applied if connection data is set to be remembered
account_number = 555
authorized = mt5.login(account_number)

if authorized:
    print(f'connected to account #{account_number}')
else:
    print(
        f'failed to connect at account #{account_number}, error code: {mt5.last_error()}'
    )

# store the equity of your account
account_info = mt5.account_info()
if account_info is None:
    raise RuntimeError('Could not load the account equity level.')
else:
    equity = float(account_info[10])
Example #30
0
mt5.initialize()                    # Connecting the program to MT5
print(mt5.version(), '\n')          # Version info of MT5 software

#___________Creating a terminal info dictionary____________#
trm_dict = mt5.terminal_info()._asdict()        # status info of the MT5 terminal
for i in trm_dict:
    print("{0}: {1}".format(i, trm_dict[i]))

#____________Creating an account info dictionary____________#
account_dict = mt5.account_info()._asdict()     # various information of the logdin account
for i in account_dict:
    print(i, ':', account_dict[i])

#_______________puttng info in a pandas DataFrame_______________#
account_df = pd.DataFrame(list(account_dict.items()), columns=['property', 'value'])
trm_df = pd.DataFrame(list(trm_dict.items()), columns=['property', 'value'])

#_________________Brokerage account Login example_________________________#
'''SYNTAX: mt5.login(loginID, server='server_name', password='******')'''

loginID = 00000000                  # Your login ID
authentication = mt5.login(loginID, server='server_name', password='******')

if authentication:
    print(mt5.account_info())
else:
    print("failed to login to trade account {0}".format(loginID))


print(mt5.last_error())             # Returns error if any
mt5.shutdown()                      # Break connection with MT5 Terminal