2

I have made a trading expert that goes through candlesticks to check if a signal has been found then execute buy , sell orders

for i in range (len(df['Open'])) : 
  if some logic :
     buy or sell

Now I want this expert to work on real-time data, not a historical one and I struggle with making the logic on how it'd work

what I want to do is:

Looking for the last 30 bars then make some calculations on them, then go in a loop to check the last 2 candlesticks to see if some signal has been found ..I want the loop to work every 4 hours since I'm working on 4h timeframe, so with every new candlestick

I'm trying to use MetaTrader5 library

copy_rates_from_pos(
       symbol,       // symbol name
       timeframe,    // timeframe
       start_pos,    // initial bar index
       count         // number of bars
       )

this code would help me find the last 30 bars but still can't get my head around on how to make the for loop !

mr.m
  • 312
  • 4
  • 15
  • `rates = mt5.copy_rates_from_pos("EURUSD",mt5.TIMEFRAME_D1, 0, 30)` `for rate in rates: print(rate)` – Daniel Kniaz May 13 '20 at 14:51
  • @DanielKniaz thanks for your comment .so I put my strategy inside this for loop of rates? and after I get a signal or not, the loop will exit! , how can I make this run indefinitely? – mr.m May 13 '20 at 15:03
  • I do not know what is your strategy about. probably you need to receive the signal as a result of analysis (looping) those 30 bars. After you receive a signal - go further with sending a trade. Maybe you should start from as simple strategy as possible, if you have such questions :) – Daniel Kniaz May 13 '20 at 17:25
  • @DanielKniaz thanks again for the help , `rates = mt5.copy_rates_from_pos("EURUSD",mt5.TIMEFRAME_D1, 0, 30) for rate in rates : if signal : buy or sell ` my question here is after exiting the loop (30bars ), I need to enter the loop again once a new candlestick is formed! should I put the whole code above in a "while true" to do so ?! – mr.m May 13 '20 at 17:35
  • 1
    it should start once per bar I suppose. set a timer or sth like that, or call MT5 every second – Daniel Kniaz May 14 '20 at 07:09

1 Answers1

4

you could use something like this

import pytz
import pandas as pd
import MetaTrader5 as mt5
import time
from datetime import datetime
from threading import Timer



server_name = "AMPGlobalUSA-Demo"
server_num = # your server num
password = # password



#------------------------------------------------------------------------------
def actualtime():
    # datetime object containing current date and time
    now = datetime.now()
    dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
    #print("date and time =", dt_string)
    return str(dt_string)
#------------------------------------------------------------------------------
def sync_60sec(op):

    info_time_new = datetime.strptime(str(actualtime()), '%d/%m/%Y %H:%M:%S')
    waiting_time = 60 - info_time_new.second

    t = Timer(waiting_time, op)
    t.start()

    print(actualtime(), f'waiting till next minute and 00 sec...')
#------------------------------------------------------------------------------
def program(symbol):
    if not mt5.initialize(login=server_num, server=server_name, password=password):
        print("initialize() failed, error code =",mt5.last_error())
        quit()

    timezone = pytz.timezone("Etc/UTC")
    utc_from = datetime.now()

    ######### Change here the timeframe
    rates = mt5.copy_rates_from(symbol, mt5.TIMEFRAME_M1, utc_from, 70)

    mt5.shutdown()

    rates_frame = pd.DataFrame(rates)
    rates_frame['time']=pd.to_datetime(rates_frame['time'], unit='s')

    # If you want to work only with open, high, low, close you could use
    #rates_frame = rates_frame.drop(['tick_volume', 'real_volume'], axis=1)

    print(f"\n", actualtime(),f"|| waiting for signals {symbol} ||\n")

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

    point = mt5.symbol_info(symbol).point
    price = mt5.symbol_info_tick(symbol).ask

    request = {
                "action": mt5.TRADE_ACTION_PENDING,
                "symbol": symbol,
                "volume": 1.0,
                "type": mt5.ORDER_TYPE_BUY_LIMIT,
                "price": price,
                "sl": price + 40 * point,
                "tp": price - 80 * point,
                "deviation": 20,
                "magic": 234000,
                "comment": "st_1_min_mod_3",
                "type_time": mt5.ORDER_TIME_GTC,
                "type_filling": mt5.ORDER_FILLING_RETURN,
            }


    condition_buy_1 = (
        (rates_frame.close.iloc[-2] > rates_frame.open.iloc[-2])& 
        (rates_frame.close.iloc[-2] > rates_frame.close.iloc[-3])
    )

    if condition_buy_1:
        #result = mt5.order_send(request)
        print('Sending Order!')


# Im using AMPGlobalUSA-Demo Server
# starting mt5
if not mt5.initialize(login=server_num, server=server_name, password=password):
    print("initialize() failed, error code =",mt5.last_error())
    quit()          
#------------------------------------------------------------------------------
#                   S T A R T I N G   M T 5 
#------------------------------------------------------------------------------
authorized=mt5.login(server_num, password=password)
if authorized:
    account_info=mt5.account_info()
    if account_info!=None:       
        account_info_dict = mt5.account_info()._asdict()
        df=pd.DataFrame(list(account_info_dict.items()),columns=['property','value'])
        print("account_info() as dataframe:")
        print(df)
else:
    print(f"failed to connect to trade account {server_num} with password={password}, error code =",mt5.last_error())

mt5.shutdown()
#------------------------------------------------------------------------------
def trading_bot():
    symbol_1 = 'EURUSD'
    symbol_2 = 'EURCAD'
    while True:
        program(symbol_1)
        program(symbol_2)
        time.sleep(59.8) # it depends on your computer and ping

sync_60sec(trading_bot)

Here you have the basics how to connect and operate with Python and MT5. You can save it as py file. And you have the first script looking for signals in 1 min chart for your symbol. You could have two different scripts mor looking for signals in 5 and 15 min charts, (program_5min.py and program_15min.py). You should then, add a new sync function. For example, for 5 minutes you have to wait for one hour and 0,5,10,15 minutes and so one.

Hope it works for you, have fun!