Pytrader - API For MT4 (V2.07)
Pytrader - API For MT4 (V2.07)
Table of Contents
Introduction............................................................................................................................................. 4
Functions. ................................................................................................................................................ 4
1. Instantiation. ........................................................................................................................... 4
2. Connect to server .................................................................................................................... 4
3. Check connection. ................................................................................................................... 5
4. Change time out value ............................................................................................................ 5
5. Retrieve broker server time. ................................................................................................... 5
6. Get static account information. .............................................................................................. 6
7. Get dynamic account information........................................................................................... 6
8. Get instrument information .................................................................................................... 6
9. Get last tick information.......................................................................................................... 7
10. Get actual bar information .................................................................................................. 7
11. Get last x ticks from now ..................................................................................................... 8
12. Get last x bars from now ..................................................................................................... 8
13. Get a specific bar for list of instruments ............................................................................. 8
14. Open order .......................................................................................................................... 8
15. Set SL and TP for position .................................................................................................... 9
16. Set SL and TP for order (pendings) ...................................................................................... 9
17. Get all (open)orders ............................................................................................................ 9
18. Get all deleted orders within window ................................................................................. 9
19. Get all deleted orders ........................................................................................................ 10
20. Get all (open) positions ..................................................................................................... 10
21. Get all closed positions within window ............................................................................. 10
22. Get all closed positions...................................................................................................... 10
23. Close_position_by_ticket .................................................................................................. 11
24. Close_position_partial_by_ticket ...................................................................................... 11
25. Delete order by ticket ........................................................................................................ 11
26. Get all instruments in broker watch list ............................................................................ 12
27. Get profit and loss over specified time period .................................................................. 12
28. Reset SL and TP for a position ........................................................................................... 12
29. Reset SL and TP for an order ............................................................................................. 12
30. Set bar date ascending or descending .............................................................................. 13
22-11.2020 V2.01 Changed authorization, added authorization indicator for MT4 market
place
09-10-2020 V1.05 Removed DLL for MT4 EA and updated documentation for python script
• An EA running on MT4 terminal. This EA works as the socket server. The EA has to run all the
time. The EA will react on requests from the “Pytrader_API”(python script). At the end of this
document is explained how to install the EA on MT4 terminal.
• A python script, name “Pytrader_API”, which functions as the connection with the MT4 EA
Functions.
General
Time out is set to 60 seconds as default. There is a separate function to change the ‘time out’ time.
Input parameters/settings are in green, results are in blue.
1. Instantiation.
## declaration
## instantiate
MT = Pytrader_API()
Utils is a subfolder in my python project. Can be any other sub folder, or just the main folder
2. Connect to server
At connection time a broker instrument dictionary has to be passed as a parameter. This dictionary is
a lookup table for translating general instrument/symbol names into specific broker
instrument/symbol names. This is for compatibility with Pytrader_API.
11111 = port (number). Server socket of the MT4 EA must use same port.
brokerInstrumentLookup = dictionary
3. Check connection.
CheckAlive= MT.Check_connection()
Result = MT.Set_timeout(timeout_in_seconds=120)
ServerTime = MT.Get_broker_server_time()
StaticInfo = MT.Get_static_account_info()
DynamicInfo = MT.Get_dynamic_account_info()
InstrumentInfo = MT.Get_instrument_info(instrument='EURUSD')
‘EURUSD’ = instrument.
InstrumentInfo = dictionary with the following information(if instrument not known, result is
“none”):
Instrument = EURUSD
digits = 5
max_lotsize = 200.0
min_lotsize = 0.01
lot_step = 0.01
point = 1e-05
tick_size = 1e-05
tick_value = 1.0
LastTick = MT.Get_last_tick_info(instrument='EURUSD')
Remarks.
• This function can be used for live streaming of tick data.
ActualBar = MT.Get_actual_bar_info(instrument='EURUSD',
timeframe=MT.get_timeframe_value('H4'))
MT.get_timeframe_value('H4') = timeframe/period.
This function can be used for live streaming of actual bar data
LastBars = MT.Get_last_x_bars_from_now(instrument='EURUSD',
timeframe=MT.get_timeframe_value('M1'), nbrofbars=1000)
‘EURUSD’ = instrument.
‘buy’ = order type (‘buy’, ‘sell’, ‘buy_stop’, ‘sell_stop’, ‘buy_limit’, ‘sell_limit’).
0.02 = volume/lot size.
0.0 = open price. For market orders price will be zero (0.0), for pending orders price must
have an appropriate value.
10 = slippage.
1000 = magic number.
1.0830 = stop loss. The stop loss value is a market price (not in delta pips), of 0.0 then no stop
loss set.
1.0950 = take profit. The take profit is a market price (not in delta pips), if 0.0 then no take
profit set.
NewOrder = ticket, if ticket has the value -1, placing of the order failed.
Remark:
If a ticket has the value -1, the following properties can be checked:
• MT.order_return_message. It is a string with the reason for fail.
• MT.order_error. It is an integer with MT4 error code.
AllOrders = MT.Get_all_orders()
AllOrders = MT.Get_all_deleted_orders_within_window(
(date_from=datetime(2020, 6, 3, tzinfo=timezone), date_to=datetime.now()))
AllOrders = MT.Get_all_deleted_orders()
AllPositions = MT.Get_all_open_positions()
timezone = pytz.timezone("Etc/UTC")
AllClosedPositions = MT.Get_closed_positions_within_window
(date_from=datetime(2020, 6, 3, tzinfo=timezone), date_to=datetime.now())
Be aware:
• The positions must be opened and closed within the window
• That there is probably a difference between local time and broker server time. Positions are
in broker server time.
AllClosedPositions = MT.Get_all_closed_positions()
Be aware:
23. Close_position_by_ticket
ClosePosition = MT.Close_position_by_ticket(ticket=597318718)
If ok = False, the properties MT.order_return_message and MT.order_error can be checked for the
reason.
24. Close_position_partial_by_ticket
PartialClose = MT.Close_position_partial_by_ticket(ticket=367014000,
volume_to_close=0.01)
If ok = False, the properties MT.order_return_message and MT.order_error can be checked for the
reason.
Remarks:
• If volume_to_close is smaller than minimum volume, the volume_to_close will be changed
into minimum volume.
• After successful partial close the position ticket number for MT4 terminal will change
DeleteOrder = MT.Delete_order_by_ticket(ticket=49988037)
Broker_marketwatch_list = MT.Get_instruments()
timezone = pytz.timezone("Etc/UTC")
Reset = MT.Reset_sl_and_tp_for_position(ticket=53136604)
Reset = bool, True or False, MT.order_return_message and MT.order_error give more information
Reset = MT.Reset_sl_and_tp_for_order(ticket=53136604)
Reset = bool, True or False, MT.order_return_message and MT.order_error give more information
In MT4/5 the actual bar has index 0([0]). So the BT will do the same as default. You can do the
opposite by using this function.
Result = MT.Set_date_asc_or_desc(asc_desc=True)
License = MT.Check_license()
Trading_allowed = MT.Check_trading_allowed(instrument=’EURUSD’)
Remarks:
• This EA does not trade on its own. All commands have to come from your own coded strategy in
a python script.
• The amount of historical data to retrieve depends on the history available on the MT4
• This is also time frame and broker dependent.
• If many data are needed first set the max number of bars per chart to a higher value under tools,
options, graphs
Next you can scroll back in a chart for the instrument you need the M1 bars for. There are also scripts
on the internet for downloading historical data. Google is your friend.
[ICM]
AUDCAD: AUDCAD
AUDCHF: AUDCHF
AUDJPY: AUDJPY
AUDNZD: AUDNZD
AUDUSD: AUDUSD
BTCUSD: BTCUSD
CADCHF: CADCHF
CADJPY: CADJPY
CHFJPY: CHFJPY
CHFSGD: CHFSGD
EURAUD: EURAUD
With the next code you can easy select the lookup table for a typical broker
The python script only recognizes the instruments defined in the lookup dictionary.
#Read in config
CONFIG_FILE= "Instrument.conf"
config = configparser.ConfigParser()
config.read(CONFIG_FILE)
brokerInstrumentsLookup = config_instruments(config,'ICM')