Gr8/trade.py

98 lines
2.7 KiB
Python
Raw Permalink Normal View History

2025-09-10 15:02:31 +03:00
import MetaTrader5 as mt5
import logging
import time
# -----------------------------
# Logging
# -----------------------------
logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(levelname)s | %(message)s")
log = logging.getLogger()
# -----------------------------
# Parameters
# -----------------------------
SYMBOLS = ["XAUUSD", "US30", "USTEC"]
LOT_SIZE = 1
ORDER_TYPE = mt5.ORDER_TYPE_SELL # Market sell
# -----------------------------
# Initialize MT5
# -----------------------------
if not mt5.initialize():
log.error(f"MT5 initialize failed: {mt5.last_error()}")
quit()
log.info("Connected to MT5 terminal")
# -----------------------------
# Function to place a market sell
# -----------------------------
def place_sell(symbol, lot):
info = mt5.symbol_info(symbol)
if info is None:
log.error(f"{symbol} not found")
return None
# Ensure symbol is visible
if not info.visible:
if not mt5.symbol_select(symbol, True):
log.error(f"Cannot select {symbol}")
return None
# Check AutoTrading
if not mt5.terminal_info().trade_allowed:
log.error(f"AutoTrading disabled in terminal")
return None
# Adjust lot to valid step
lot = max(info.volume_min, min(lot, info.volume_max))
lot = round((lot // info.volume_step) * info.volume_step, 2)
# Determine correct filling type
if info.filling_mode & mt5.ORDER_FILLING_FOK:
filling = mt5.ORDER_FILLING_FOK
elif info.filling_mode & mt5.ORDER_FILLING_IOC:
filling = mt5.ORDER_FILLING_IOC
else:
filling = mt5.ORDER_FILLING_RETURN
# Market price
tick = mt5.symbol_info_tick(symbol)
if tick is None:
log.error(f"Cannot get tick for {symbol}")
return None
price = tick.bid # Sell at bid
request = {
"action": mt5.TRADE_ACTION_DEAL,
"symbol": symbol,
"volume": lot,
"type": ORDER_TYPE,
"price": price,
"deviation": 50,
"magic": 234000,
"comment": "Python Market Sell",
"type_time": mt5.ORDER_TIME_GTC,
"type_filling": filling
}
result = mt5.order_send(request)
if result.retcode != mt5.TRADE_RETCODE_DONE:
log.error(f"Sell order for {symbol} failed: {result.retcode}")
return result
else:
log.info(f"Sell order for {symbol} placed successfully: {result}")
return result
# -----------------------------
# Place trades for all symbols
# -----------------------------
for sym in SYMBOLS:
place_sell(sym, LOT_SIZE)
time.sleep(1) # Small delay between orders
# -----------------------------
# Shutdown MT5
# -----------------------------
mt5.shutdown()
log.info("MT5 shutdown complete")