いよいよ、Pythonで作るEAのフレームワークも完成間地かとなりました。
EAのフレームワークとしては、大まかには以下の部品で成り立ちます。
- データの取得と整形
- トレードロジックの構築
- 注文とポジション管理
- メインループの設定

美来
やっとここまで来た感じ。ポジション管理ね。

ネズミ先生
エントリーの関数は前回でできたので、エグジットする関数だチュー。
ポジションを閉じる関数
def close_all_positions(symbol):
positions = mt5.positions_get(symbol=symbol)
if positions is None:
print("No positions to close")
return None
for position in positions:
action = 'sell' if position.type == mt5.ORDER_TYPE_BUY else 'buy'
lot_size = position.volume
close_request = {
'action': mt5.TRADE_ACTION_DEAL,
'symbol': symbol,
'volume': lot_size,
'type': mt5.ORDER_TYPE_BUY if action == 'buy' else mt5.ORDER_TYPE_SELL,
'price': mt5.symbol_info_tick(symbol).ask if action == 'buy' else mt5.symbol_info_tick(symbol).bid,
'deviation': 10,
'magic': 234000,
'comment': 'python script close order',
'type_time': mt5.ORDER_TIME_GTC,
'type_filling': mt5.ORDER_FILLING_IOC,
}
result = mt5.order_send(close_request)
if result.retcode != mt5.TRADE_RETCODE_DONE:
print(f"Failed to close position {position.ticket}: {result.comment}")
# 目標利益幅に達したらクローズする関数。
ef trail_profit_order(symbol, target_profit):
# 銘柄のすべてのポジションを取得
positions = mt5.positions_get(symbol=symbol)
if positions is None:
print("No positions to trail")
return None
# それぞれのポジションに対して処理
for position in positions:
# 現在の利益(pips単位)を計算
current_profit_pips = position.profit / position.volume / 0.0001
# 目標利益に達しているかどうかを確認
if current_profit_pips >= target_profit:
lot_size = position.volume
action = 'sell' if position.type == mt5.ORDER_TYPE_BUY else 'buy'
# 関連するトレードをクローズ
result = place_trade(symbol, action, lot_size)
if result.retcode != mt5.TRADE_RETCODE_DONE:
print(f"Failed to close position {position.ticket}: {result.comment}")
# 自動取引の実行
while True:
# 現在のデータを取得
data = get_data(symbol, timeframe, n)
# 戦略に基づいてシグナルを生成
data = crossover_strategy(data)
# 最後のシグナルを見る(最新のシグナル)
if data['position'].iloc[-1] == 1:
print("買いシグナルが検出されました")
# 既存のポジションを閉じる
close_all_positions(symbol)
# 新しいポジションをエントリー
result = place_trade(symbol, 'buy', 0.1)
if result.retcode == mt5.TRADE_RETCODE_DONE:
print("買いポジションエントリー成功")
else:
print(f"買いポジションエントリー失敗: {result.comment}")
elif data['position'].iloc[-1] == -1:
print("売りシグナルが検出されました")
# 既存のポジションを閉じる
close_all_positions(symbol)
# 新しいポジションをエントリー
result = place_trade(symbol, 'sell', 0.1)
if result.retcode == mt5.TRADE_RETCODE_DONE:
print("売りポジションエントリー成功")
else:
print(f"売りポジションエントリー失敗: {result.comment}")
# 利益目標に達している場合にポジションをクローズ
trail_profit_order(symbol, TARGET_PROFIT)
# 5分待つ
time.sleep(300)

コメント