Python MT5 connect

 import time


import MetaTrader5 as mt
import pandas as pd
import plotly.express as px
from datetime import datetime,timedelta
import pandas_ta as ta

ticket_buy = 0
ticket_Sell = 0

mt.initialize()

id=70377459
passwod="2wmnxlsx"
investerpwd="1ezennib"
server="MetaQuotes-Demo"

# account data

mt.login(id,passwod,server)

account_info=mt.account_info()
balance=account_info.balance
equity=account_info.equity

# symbol data

num_symbols=mt.symbols_total()
ltp_1=mt.symbol_info("EURUSD")._asdict()# need to understand this
commonused_ltp=mt.symbol_info_tick("EURUSD")._asdict()# bid and ask


def buy_order():
request = {

"action":mt.TRADE_ACTION_DEAL,
"symbol":"EURUSD",
"volume":0.01,
"type":mt.ORDER_TYPE_BUY,
"price":mt.symbol_info_tick("EURUSD").ask,
"sl":0.0,
"tp":0.0,
"deviation":20,
"magic":12345,
"comment":"PYTHON SCRIPT ORDER OPEN BUY",
"type_time":mt.ORDER_TIME_GTC,
"type_filling":mt.ORDER_FILLING_IOC,
}

Buyorder=mt.order_send(request)
ticket_buy = Buyorder.order


def sell_order():
request = {

"action":mt.TRADE_ACTION_DEAL,
"symbol":"EURUSD",
"volume":0.01,
"type":mt.ORDER_TYPE_SELL,
"price":mt.symbol_info_tick("EURUSD").bid,
"sl":0.0,
"tp":0.0,
"deviation":20,
"magic":12345,
"comment":"PYTHON SCRIPT ORDER OPEN SELL",
"type_time":mt.ORDER_TIME_GTC,
"type_filling":mt.ORDER_FILLING_IOC,
}

Sellorder=mt.order_send(request)
ticket_Sell = Sellorder.order


def close_buy_position():
closerequest = {

"action":mt.TRADE_ACTION_DEAL,
"symbol":"EURUSD",
"volume":0.05,
"type":mt.ORDER_TYPE_SELL,
"price":mt.symbol_info_tick("EURUSD").ask,
"position":ticket_buy,
"sl":0.0,
"tp":0.0,
"deviation":20,
"magic":12345,
"comment":"PYTHON SCRIPT ORDER CLOSE BUY POSITION",
"type_time":mt.ORDER_TIME_GTC,
"type_filling":mt.ORDER_FILLING_IOC,
}

buy_order_close=mt.order_send(closerequest)
print(buy_order_close)

def close_sell_position():
closerequest = {

"action": mt.TRADE_ACTION_DEAL,
"symbol": "EURUSD",
"volume": 0.05,
"type": mt.ORDER_TYPE_BUY,
"price": mt.symbol_info_tick("EURUSD").bid,
"position": ticket_Sell,
"sl": 0.0,
"tp": 0.0,
"deviation": 20,
"magic": 12345,
"comment": "PYTHON SCRIPT ORDER CLOSE SELL POSITION",
"type_time": mt.ORDER_TIME_GTC,
"type_filling": mt.ORDER_FILLING_IOC,
}

sell_order_close = mt.order_send(closerequest)
print(sell_order_close)


def check_historical_performace():
BUY = False
SHORT = False
for i in range (6,len(ohlc_data)):

if(ohlc_data["sma_on_sma_5"][i-1] <= ohlc_data["sma_on_price"] [i-1] and ohlc_data["sma_on_sma_5"][i]> ohlc_data["sma_on_price"][i] and BUY==False):
print("Buy Order @ EURUSD"+str(ohlc_data["time"][i]))
BUY=True
SHORT=False
ohlc_data["BuySignal"][i] = 1
ohlc_data["SellSignal"][i]= 0




if (ohlc_data["sma_on_sma_5"][i-1] >= ohlc_data["sma_on_price"][i-1] and ohlc_data["sma_on_sma_5"][i]< ohlc_data["sma_on_price"][i] and SHORT == False ):
print("Sell Order @ EURUSD"+str(ohlc_data["time"][i]))
BUY = False
SHORT = True
ohlc_data["BuySignal"][i] = 0
ohlc_data["SellSignal"][i] = 1

BUY=False
SHORT=False

def ema_on_ema_cross():
print("Strategy Activated")
print("sma_on_sma_5 Curnent"+str(ohlc_data["sma_on_sma_5"].iloc[-2]))
print("sma_on_price Curnent"+str( ohlc_data["sma_on_price"].iloc[-2]))
print("sma_on_sma_5 past"+str(ohlc_data["sma_on_sma_5"].iloc[-3]))
print("sma_on_price Curnent"+str(ohlc_data["sma_on_price"].iloc[-3] ))

global BUY ,SHORT


for i in range (len(ohlc_data)):

if(ohlc_data["sma_on_sma_5"].iloc[-3] <= ohlc_data["sma_on_price"].iloc[-3] and ohlc_data["sma_on_sma_5"].iloc[-2] > ohlc_data["sma_on_price"].iloc[-2] and BUY==False):
print("Buy Order @ EURUSD")
BUY=True
SHORT=False
global global_var
if ticket_Sell>0:
close_sell_position()
buy_order()




if (ohlc_data["sma_on_sma_5"].iloc[-3] >= ohlc_data["sma_on_price"].iloc[-3] and ohlc_data["sma_on_sma_5"].iloc[-2] < ohlc_data["sma_on_price"].iloc[-2] and SHORT == False ):
print("Sell Order @ EURUSD")
BUY = False
SHORT = True
global ticket_buy
if ticket_buy > 0:
close_buy_position()
sell_order()



# historical ohlc ths canbe conveerted to a look to run after any timeframe you select
ohlc_data = pd.DataFrame(mt.copy_rates_range("EURUSD", mt.TIMEFRAME_M5, (datetime.now() - timedelta(days=20)), datetime.now()))

for i in range(len(ohlc_data)):
ohlc_data.loc[i, "time"] = datetime.fromtimestamp(ohlc_data.loc[i, "time"])

print(ohlc_data)
ohlc_data.to_csv("check.csv")
ohlc_data["sma_on_price"] = ta.sma(close=ohlc_data["close"], length=5)
ohlc_data["sma_on_sma_5"] = ta.sma(close=ohlc_data["sma_on_price"], length=5)
ohlc_data.to_csv("StrategyResult.csv", index=False)
ohlc_data["BuySignal"] = 0
ohlc_data["SellSignal"]= 0
# check_historical_performace()
ohlc_data.to_csv("StrategyResult.csv", index=False)
df=pd.read_csv("StrategyResult.csv")
print(df['BuySignal'].value_counts())
print(df['SellSignal'].value_counts())
run=True

while run:
# historical ohlc ths canbe conveerted to a look to run after any timeframe you select
ohlc_data = pd.DataFrame(
mt.copy_rates_range("EURUSD", mt.TIMEFRAME_M5, (datetime.now() - timedelta(days=20)), datetime.now()))

for i in range(len(ohlc_data)):
ohlc_data.loc[i, "time"] = datetime.fromtimestamp(ohlc_data.loc[i, "time"])

ohlc_data["sma_on_price"] = ta.sma(close=ohlc_data["close"], length=5)
ohlc_data["sma_on_sma_5"] = ta.sma(close=ohlc_data["sma_on_price"], length=5)
ohlc_data.to_csv("StrategyResult.csv", index=False)

ema_on_ema_cross()
time.sleep((60))



#
#
# # order (for open orders that are not filled) and position details (filled position that are still runing)
# positions= mt.positions_get( symbol='GBPUSD')
# #print(positions)
# #order history
#
# order_histor= mt.history_orders_get(datetime(2023,6,7))# number of order
# print(order_histor)
#
# # send orders
# request={
#
# "action":mt.TRADE_ACTION_DEAL,
# "symbol":"EURUSD",
# "volume":0.05,
# "type":mt.ORDER_TYPE_BUY,
# "price":mt.symbol_info_tick("EURUSD").ask,
# "sl":0.0,
# "tp":0.0,
# "deviation":20,
# "magic":12345,
# "comment":"PYTHON SCRIPT ORDER",
# "type_time":mt.ORDER_TIME_GTC,
# "type_filling":mt.ORDER_FILLING_IOC,
# }
#
# Buyorder=mt.order_send(request)
# ticket_buy = Buyorder.order
# print(Buyorder.order)
#
# # close an order
# closerequest={
#
# "action":mt.TRADE_ACTION_DEAL,
# "symbol":"EURUSD",
# "volume":0.05,
# "type":mt.ORDER_TYPE_SELL,
# "price":mt.symbol_info_tick("EURUSD").ask,
# "position":1746611026,
# "sl":0.0,
# "tp":0.0,
# "deviation":20,
# "magic":12345,
# "comment":"PYTHON SCRIPT ORDER",
# "type_time":mt.ORDER_TIME_GTC,
# "type_filling":mt.ORDER_FILLING_IOC,
# }
#
# # buy_order_close=mt.order_send(closerequest)
# # print(buy_order_close)

Comments

Popular posts from this blog

MQL5 : Add time to current time in mins

MQL5: Closed order detail