backtesting.py
backtesting.py copied to clipboard
Buy/Sell code is not working in Python 3 using MT5 API
I have write python code to close buy/sell positions with condition. I have hedging account so I have to close all open buy/sell positions separately but It is not working. my code is below
def support_trade_level(self, support, resistance, lower_support, positions):
if self.close <= support + self.buy_point1 and self.close >= support - self.buy_point2 and positions < 10:
if self.low > self.previous_low:
open_positions = mt5.positions_get(symbol="USA500")
for position in open_positions:
if position.type == mt5.ORDER_TYPE_SELL:
result = mt5.order_close(position.ticket, position.volume)
print(f" Result {result}")
self.buy(
price=self.mt5.symbol_info_tick(self.symbol).ask,
sl=support - self.slo_buy_point, #self.mt5.symbol_info_tick(self.symbol).ask - self.slo_buy_point,
tp=resistance + self.tp_buy_point #self.mt5.symbol_info_tick(self.symbol).ask + self.tp_buy_point
)
def resistance_trade_level(self, support, resistance, upper_resistance, positions):
if self.close <= resistance + self.buy_point1 and self.close >= resistance - self.buy_point2 and positions < 10:
if self.high > self.previous_high:
open_positions = mt5.positions_get(symbol="USA500")
for position in open_positions:
if position.type == mt5.ORDER_TYPE_SELL:
result = mt5.order_close(position.ticket, position.volume)
print(f" Result {result}")
self.buy(
price=self.mt5.symbol_info_tick(self.symbol).ask,
sl=resistance - self.slo_buy_point, #self.mt5.symbol_info_tick(self.symbol).ask - self.slo_buy_point,
tp=upper_resistance + self.tp_buy_point #self.mt5.symbol_info_tick(self.symbol).ask + self.tp_buy_point
)
is there any solution to close open buy/sell positions separately when required?
this code allow to open buy/sell position successfully but where i write code to close my open positions when candles are red/green on 1 minute chart so it will close my open positions, but this code is not working however it is not giving any error as well. code run smoothly, took buy/sell positions a the given levels but didn't close any position except it touch its given TP or SLO level which is not desired. code for closing position is below,
if self.high > self.previous_high:
open_positions = mt5.positions_get(symbol="USA500")
for position in open_positions:
if position.type == mt5.ORDER_TYPE_SELL:
result = mt5.order_close(position.ticket, position.volume)```