TestPython_OrderOpen.py
import MetaTrader5 as mt5
# MT5の起動と接続
if not mt5.initialize():
print("MT5への接続に失敗しました")
else:
print("MT5に接続しました")
print("MT5 バージョン:", mt5.__version__)
# 口座情報を取得
account_info = mt5.account_info()
if account_info is not None:
print(f"ログインID: {account_info.login}")
print(f"残高: {account_info.balance}")
print(f"証拠金: {account_info.equity}")
else:
print("口座情報を取得できません")
# MT5の接続終了
mt5.shutdown()
TestPython_OrderOpen.py
import MetaTrader5 as mt5
#import pandas as pd
# MT5の初期化
mt5.initialize()
# 通貨 ドル円
symbol = "USDJPY"
# 注文パラメータの作成
order = {
"action": mt5.TRADE_ACTION_DEAL,
"symbol": symbol,
"volume": 0.01,
"type": mt5.ORDER_TYPE_BUY,
"price": mt5.symbol_info_tick(symbol).ask,
"deviation": 10,
"magic": 234000,
"comment": "python script order",
"type_time": mt5.ORDER_TIME_GTC,
"type_filling": mt5.ORDER_FILLING_IOC,
}
result = mt5.order_send(order)
if result.retcode == mt5.TRADE_RETCODE_DONE:
print("注文が正常に完了しました。")
else:
print(f"注文エラー: {result.retcode}")
# MT5の終了
mt5.shutdown()
その1 (作成日:2025-10-20)
ポジションを持っていなければ注文を入れて、利益になれば決済をします
import MetaTrader5 as mt5
import time
mt5.initialize()
# Input設定
symbol = 'GOLD' # 取引対象
first_lot = 0.01 # 初期ロット
nanpin_range = 200 # ナンピン幅
profit_target = 10 # 利益目標
magic_number = 10001 # マジックナンバー
slippage = 10 # スリッページ
sleep_sec = 5 # N秒間スリープ
tick_time = 0;
point=mt5.symbol_info(symbol).point # 価格の最小単位
#-- <無碍ループ>
while 1:
symbol_tick=mt5.symbol_info_tick(symbol) # symbolのtick情報を取得
# 確認用
#print ("symbol_tick=", symbol_tick)
#-- tick時間が前回値と異なれる場合
if (tick_time != symbol_tick.time):
tick_time = symbol_tick.time
#print ("★tick_time=", tick_time)
#-- N秒間スリープ
#print("処理を開始します。")
time.sleep(sleep_sec)
#print("3秒後に処理が再開されました。")
#-- <ポジションの確認>
buy_position = 0 # buyポジション数の初期化
sell_position = 0 # sellポジション数の初期化
buy_profit = 0 # buy_profitの初期化
sell_profit = 0 # sell_profitの初期化
current_buy_lot = 0 # 最新のbuyポジションのlot数の初期化
current_sell_lot = 0 # 最新のsellポジションのlot数の初期化
positions=mt5.positions_get(group='*'+symbol+'*') # ポジション情報を取得
# 確認用
#print ("positions=", positions)
for i in range(len(positions)): # 全てのポジションを確認
order_type = positions[i][5] # buyかsellか取得
profit = positions[i][15] # ポジションの含み損益を取得
if order_type == 0: # buyポジションの場合
buy_position += 1 # buyポジションのカウント
buy_profit += profit # buyポジションの含み損益に加算
current_buy_lot = positions[i][9] # 最新のbuyポジションのlot数を取得
current_buy_price = positions[i][10] # 最新のbuyポジションの取得価格を取得
if order_type == 1: # sellポジションの場合
sell_position += 1 # sellポジションのカウント
sell_profit += profit # sellポジションの含み損益に加算
current_sell_lot = positions[i][9] # 最新のsellポジションのlot数を取得
current_sell_price = positions[i][10] # 最新のsellポジションの取得価格を取得
#-- </ポジションの確認>
#-- <新規エントリー>
# <新規buyエントリー>
if buy_position == 0: # buyポジションがない場合
#print ("buy_position=0")
request = {
'symbol': symbol, # 通貨ペア(取引対象)
'action': mt5.TRADE_ACTION_DEAL, # 成行注文
'type': mt5.ORDER_TYPE_BUY, # 成行買い注文
'volume': first_lot, # ロット数
'price': symbol_tick.ask, # 注文価格
'deviation': slippage, # スリッページ
'comment': 'first_buy', # 注文コメント
'magic': magic_number, # マジックナンバー
'type_time': mt5.ORDER_TIME_GTC, # 注文有効期限
'type_filling': mt5.ORDER_FILLING_IOC, # 注文タイプ
}
#print ("★新規エントリー buy")
result = mt5.order_send(request)
#print (result)
if result.retcode == mt5.TRADE_RETCODE_DONE:
print ("注文成功")
#print(f"{order_type.upper()} 注文成功: {symbol} @ {price}")
else:
print ("注文失敗")
#print(f"{order_type.upper()} 注文失敗: {result.comment}")
# </新規buyエントリー>
# <新規sellエントリー>
if sell_position == 0: # sellポジションがない場合
request = {
'symbol': symbol, # 通貨ペア(取引対象)
'action': mt5.TRADE_ACTION_DEAL, # 成行注文
'type': mt5.ORDER_TYPE_SELL, # 成行買い注文
'volume': first_lot, # ロット数
'price': symbol_tick.bid, # 注文価格
'deviation': slippage, # スリッページ
'comment': 'first_sell', # 注文コメント
'magic': magic_number, # マジックナンバー
'type_time': mt5.ORDER_TIME_GTC, # 注文有効期限
'type_filling': mt5.ORDER_FILLING_IOC, # 注文タイプ
}
result = mt5.order_send(request)
# </新規sellエントリー>
#-- </新規エントリー>
#-- <追加エントリー>
# <追加buyエントリー>
#print ("buy_position=", buy_position)
#print ("symbol_tick.ask=", symbol_tick.ask)
if buy_position > 0 and symbol_tick.ask < current_buy_price - nanpin_range * point:
request = {
'symbol': symbol, # 通貨ペア(取引対象)
'action': mt5.TRADE_ACTION_DEAL, # 成行注文
'type': mt5.ORDER_TYPE_BUY, # 成行買い注文
'volume': round(current_buy_lot * 1.5+0.001,2), # ロット数
'price': symbol_tick.ask, # 注文価格
'deviation': slippage, # スリッページ
'comment': 'nanpin_buy', # 注文コメント
'magic': magic_number, # マジックナンバー
'type_time': mt5.ORDER_TIME_GTC, # 注文有効期限
'type_filling': mt5.ORDER_FILLING_IOC, # 注文タイプ
}
result = mt5.order_send(request)
# </追加buyエントリー>
# <追加sellエントリー>
if sell_position > 0 and symbol_tick.bid > current_sell_price + nanpin_range * point:
request = {
'symbol': symbol, # 通貨ペア(取引対象)
'action': mt5.TRADE_ACTION_DEAL, # 成行注文
'type': mt5.ORDER_TYPE_SELL, # 成行売り注文
'volume': round(current_sell_lot * 1.5+0.001,2), # ロット数
'price': symbol_tick.bid, # 注文価格
'deviation': slippage, # スリッページ
'comment': 'nanpin_sell', # 注文コメント
'magic': magic_number, # マジックナンバー
'type_time': mt5.ORDER_TIME_GTC, # 注文有効期限
'type_filling': mt5.ORDER_FILLING_IOC, # 注文タイプ
}
result = mt5.order_send(request)
# </追加sellエントリー>
#-- </追加エントリー>
#-- <クローズ>
# <buyクローズ>
if buy_position > 0 and buy_profit > profit_target * buy_position:
for i in range(len(positions)):
ticket=positions[i][0] # チケットナンバーを取得
order_type = positions[i][5] # buyかsellか取得
lot = positions[i][9] # lot数を取得
if order_type == 0: # buyポジションをクローズ
request = {
'symbol': symbol, # 通貨ペア(取引対象)
'action': mt5.TRADE_ACTION_DEAL, # 成行注文
'type': mt5.ORDER_TYPE_SELL, # 成行売り注文
'volume': lot, # ロット数
'price': symbol_tick.bid, # 注文価格
'deviation': slippage, # スリッページ
'type_time': mt5.ORDER_TIME_GTC, # 注文有効期限
'type_filling': mt5.ORDER_FILLING_IOC, # 注文タイプ
'position':ticket # チケットナンバー
}
result = mt5.order_send(request)
# </buyクローズ>
# <sellクローズ>
if sell_position > 0 and sell_profit > profit_target * sell_position:
for i in range(len(positions)):
ticket=positions[i][0] # チケットナンバーを取得
order_type = positions[i][5] # buyかsellか取得
lot = positions[i][9] # lot数を取得
if order_type == 1: # sellポジションをクローズ
request = {
'symbol': symbol, # 通貨ペア(取引対象)
'action': mt5.TRADE_ACTION_DEAL, # 成行注文
'type': mt5.ORDER_TYPE_BUY, # 成行買い注文
'volume': lot, # ロット数
'price': symbol_tick.ask, # 注文価格
'deviation': slippage, # スリッページ
'type_time': mt5.ORDER_TIME_GTC, # 注文有効期限
'type_filling': mt5.ORDER_FILLING_IOC, # 注文タイプ
'position':ticket # チケットナンバー
}
result = mt5.order_send(request)
# </sellクローズ>
#-- </クローズ>
#-- </無碍ループ>
mt5.shutdown()
その2 (作成日:2025-10-20)
上記の その1 から処理を追加しました
新規注文、追加注文、決済を設定で制御できるようにしました
import MetaTrader5 as mt5
import time
mt5.initialize()
# <Input設定>
symbol = 'GOLD' # 取引対象
first_lot = 0.01 # 初期ロット
nanpin_range = 200 # ナンピン幅
profit_target = 10 # 利益目標
magic_number = 10001 # マジックナンバー
slippage = 10 # スリッページ
sleep_sec = 5 # while()の無限ループ N秒間スリープ
# 新規注文
use_NewOrder = True; # True|False
use_NewOrderBuy = True; # True|False (True=新規買い注文する False=新規買い注文しない)
use_NewOrderSell = True; # True|False (True=新規売り注文する False=新規売り注文しない)
# 追加注文
use_NanpinOrder = True; # True|False
use_NanpinOrderBuy = True; # True|False (True=追加買い注文する False=追加買い注文しない)
use_NanpinOrderSell = True; # True|False (True=追加売り注文する False=追加売り注文しない)
# 決済
use_close = True; # True|False
use_closeBuy = True; # True|False (True=買い決済する False=買い決済しない)
use_closeSell = True; # True|False (True=売り決済する False=売り決済しない)
# </Input設定>
point=mt5.symbol_info(symbol).point # 価格の最小単位
tick_time = 0;
#-- <無碍ループ>
while 1:
symbol_tick=mt5.symbol_info_tick(symbol) # symbolのtick情報を取得
# 確認用
#print ("symbol_tick=", symbol_tick)
#-- tick時間が前回値と異なれる場合
if (tick_time != symbol_tick.time):
tick_time = symbol_tick.time
#print ("★tick_time=", tick_time)
#-- N秒間スリープ
#print("処理を開始します。")
time.sleep(sleep_sec)
#print("3秒後に処理が再開されました。")
#-- <ポジションの確認>
buy_position = 0 # buyポジション数の初期化
sell_position = 0 # sellポジション数の初期化
buy_profit = 0 # buy_profitの初期化
sell_profit = 0 # sell_profitの初期化
current_buy_lot = 0 # 最新のbuyポジションのlot数の初期化
current_sell_lot = 0 # 最新のsellポジションのlot数の初期化
positions=mt5.positions_get(group='*'+symbol+'*') # ポジション情報を取得
# 確認用
#print ("positions=", positions)
for i in range(len(positions)): # 全てのポジションを確認
order_type = positions[i][5] # buyかsellか取得
profit = positions[i][15] # ポジションの含み損益を取得
if order_type == 0: # buyポジションの場合
buy_position += 1 # buyポジションのカウント
buy_profit += profit # buyポジションの含み損益に加算
current_buy_lot = positions[i][9] # 最新のbuyポジションのlot数を取得
current_buy_price = positions[i][10] # 最新のbuyポジションの取得価格を取得
if order_type == 1: # sellポジションの場合
sell_position += 1 # sellポジションのカウント
sell_profit += profit # sellポジションの含み損益に加算
current_sell_lot = positions[i][9] # 最新のsellポジションのlot数を取得
current_sell_price = positions[i][10] # 最新のsellポジションの取得価格を取得
#-- </ポジションの確認>
#-- <新規エントリー>
if use_NewOrder == True:
# <新規buyエントリー>
if use_NewOrderBuy == True:
if buy_position == 0: # buyポジションがない場合
request = {
'symbol': symbol, # 通貨ペア(取引対象)
'action': mt5.TRADE_ACTION_DEAL, # 成行注文
'type': mt5.ORDER_TYPE_BUY, # 成行買い注文
'volume': first_lot, # ロット数
'price': symbol_tick.ask, # 注文価格
'deviation': slippage, # スリッページ
'comment': 'first_buy', # 注文コメント
'magic': magic_number, # マジックナンバー
'type_time': mt5.ORDER_TIME_GTC, # 注文有効期限
'type_filling': mt5.ORDER_FILLING_IOC, # 注文タイプ
}
# 新規買い注文 実行
result = mt5.order_send(request)
print ("新規買い注文結果:", result)
# 結果出力
if result.retcode == mt5.TRADE_RETCODE_DONE:
print ("新規買い注文:成功")
#print(f"{order_type.upper()} 注文成功: {symbol} @ {price}")
else:
print ("新規買い注文:失敗")
#print(f"{order_type.upper()} 注文失敗: {result.comment}")
# </新規buyエントリー>
# <新規sellエントリー>
if use_NewOrderSell == True:
if sell_position == 0: # sellポジションがない場合
request = {
'symbol': symbol, # 通貨ペア(取引対象)
'action': mt5.TRADE_ACTION_DEAL, # 成行注文
'type': mt5.ORDER_TYPE_SELL, # 成行買い注文
'volume': first_lot, # ロット数
'price': symbol_tick.bid, # 注文価格
'deviation': slippage, # スリッページ
'comment': 'first_sell', # 注文コメント
'magic': magic_number, # マジックナンバー
'type_time': mt5.ORDER_TIME_GTC, # 注文有効期限
'type_filling': mt5.ORDER_FILLING_IOC, # 注文タイプ
}
# 新規売り注文 実行
result = mt5.order_send(request)
print ("新規売り注文結果:", result)
# 結果出力
if result.retcode == mt5.TRADE_RETCODE_DONE:
print ("新規売り注文:成功")
else:
print ("新規売り注文:失敗")
# </新規sellエントリー>
#-- </新規エントリー>
#-- <追加エントリー>
if use_NanpinOrder == True:
# <追加buyエントリー>
if use_NanpinOrderBuy == True:
if buy_position > 0 and symbol_tick.ask < current_buy_price - nanpin_range * point:
request = {
'symbol': symbol, # 通貨ペア(取引対象)
'action': mt5.TRADE_ACTION_DEAL, # 成行注文
'type': mt5.ORDER_TYPE_BUY, # 成行買い注文
'volume': round(current_buy_lot * 1.5+0.001,2), # ロット数
'price': symbol_tick.ask, # 注文価格
'deviation': slippage, # スリッページ
'comment': 'nanpin_buy', # 注文コメント
'magic': magic_number, # マジックナンバー
'type_time': mt5.ORDER_TIME_GTC, # 注文有効期限
'type_filling': mt5.ORDER_FILLING_IOC, # 注文タイプ
}
# 追加買い注文 実行
result = mt5.order_send(request)
print ("追加買い注文結果:", result)
# 結果出力
if result.retcode == mt5.TRADE_RETCODE_DONE:
print ("追加買い注文:成功")
else:
print ("追加買い注文:失敗")
# </追加buyエントリー>
# <追加sellエントリー>
if use_NanpinOrderSell == True:
if sell_position > 0 and symbol_tick.bid > current_sell_price + nanpin_range * point:
request = {
'symbol': symbol, # 通貨ペア(取引対象)
'action': mt5.TRADE_ACTION_DEAL, # 成行注文
'type': mt5.ORDER_TYPE_SELL, # 成行売り注文
'volume': round(current_sell_lot * 1.5+0.001,2), # ロット数
'price': symbol_tick.bid, # 注文価格
'deviation': slippage, # スリッページ
'comment': 'nanpin_sell', # 注文コメント
'magic': magic_number, # マジックナンバー
'type_time': mt5.ORDER_TIME_GTC, # 注文有効期限
'type_filling': mt5.ORDER_FILLING_IOC, # 注文タイプ
}
# 追加売り注文 実行
result = mt5.order_send(request)
print ("追加売り注文結果:", result)
# 結果出力
if result.retcode == mt5.TRADE_RETCODE_DONE:
print ("追加売り注文:成功")
else:
print ("追加売り注文:失敗")
# </追加sellエントリー>
#-- </追加エントリー>
#-- <クローズ>
if use_close == True:
# <buyクローズ>
if use_closeBuy == True:
if buy_position > 0 and buy_profit > profit_target * buy_position:
for i in range(len(positions)):
ticket=positions[i][0] # チケットナンバーを取得
order_type = positions[i][5] # buyかsellか取得
lot = positions[i][9] # lot数を取得
if order_type == 0: # buyポジションをクローズ
request = {
'symbol': symbol, # 通貨ペア(取引対象)
'action': mt5.TRADE_ACTION_DEAL, # 成行注文
'type': mt5.ORDER_TYPE_SELL, # 成行売り注文
'volume': lot, # ロット数
'price': symbol_tick.bid, # 注文価格
'deviation': slippage, # スリッページ
'type_time': mt5.ORDER_TIME_GTC, # 注文有効期限
'type_filling': mt5.ORDER_FILLING_IOC, # 注文タイプ
'position':ticket # チケットナンバー
}
# 買い 決済
result = mt5.order_send(request)
print ("決済買い結果:", result)
# 結果出力
if result.retcode == mt5.TRADE_RETCODE_DONE:
print ("決済買い:成功")
else:
print ("決済買い:失敗")
# </buyクローズ>
# <sellクローズ>
if use_closeSell == True:
if sell_position > 0 and sell_profit > profit_target * sell_position:
for i in range(len(positions)):
ticket=positions[i][0] # チケットナンバーを取得
order_type = positions[i][5] # buyかsellか取得
lot = positions[i][9] # lot数を取得
if order_type == 1: # sellポジションをクローズ
request = {
'symbol': symbol, # 通貨ペア(取引対象)
'action': mt5.TRADE_ACTION_DEAL, # 成行注文
'type': mt5.ORDER_TYPE_BUY, # 成行買い注文
'volume': lot, # ロット数
'price': symbol_tick.ask, # 注文価格
'deviation': slippage, # スリッページ
'type_time': mt5.ORDER_TIME_GTC, # 注文有効期限
'type_filling': mt5.ORDER_FILLING_IOC, # 注文タイプ
'position':ticket # チケットナンバー
}
# 売り 決済
result = mt5.order_send(request)
print ("決済売り結果:", result)
# 結果出力
if result.retcode == mt5.TRADE_RETCODE_DONE:
print ("決済売り:成功")
else:
print ("決済売り:失敗")
# </sellクローズ>
#-- </クローズ>
#-- </無碍ループ>
mt5.shutdown()