Here I’ve wrote a python script using MQL5 to get total history order from MetaTrader5. here’s the code,
from_date = datetime(2020, 1, 1) to_date = datetime.now() history_orders = mt.history_orders_total(from_date, to_date ) print(history_orders)
what my requirement is I need to get from_date and to_date parameter from user. so I passed these parameter from Postman Using POST request.here is the payload
{ "fromDate" : "2020, 1, 1", "toDate": "2020, 11, 8" }
And it says,
history_orders = mt.history_orders_total(datetime(fromDate), datetime(toDate)) TypeError: an integer is required (got type str)
how can I convert these Json payloads into integers in python? here my code.
@app.route("/", methods=['POST', 'GET']) def historyOrderTotal(): fromDate = None toDate = None if request.method == 'POST': fromDate = request.json['fromDate'] toDate = request.json['toDate'] mt.initialize() history_orders = mt.history_orders_total(datetime(fromDate), datetime(toDate)) print(history_orders)
Advertisement
Answer
You care less about the integers, you want datetime
objects. You have decided that you want <year>, <month>, <day>
as your incoming serialised JSON format for dates.
So you might do:
from datetime import datetime pattern = "%Y, %m, %d" from_date = datetime.strptime(fromDate, pattern) to_date = datetime.strptime(toDate, pattern)
You might want to add validations, e.g. assert from_date <= to_date
etc. depending on your use case.
I also recommend you look into ISO 8601 date formats, as a more standardised way of serialising dates.
Debug Notes, try this based on your comments:
@app.route("/", methods=['POST', 'GET']) def historyOrderTotal(): fromDate = None toDate = None if request.method == 'POST': fromDate = request.json['fromDate'] toDate = request.json['toDate'] print("json-from:", fromDate) print("json-to:", toDate) pattern = "%Y, %m, %d" from_date = datetime.strptime(fromDate, pattern) to_date = datetime.strptime(toDate, pattern) print("parsed-from:", from_date) print("parsed-to:", to_date) if mt.initialize(): history_orders = mt.history_orders_total(from_date, to_date) print("history-orders", history_orders) else: print("initialize() failed, error code =", mt.last_error()) else: print(">> Not a POST request")