// 入力パラメータ input double ATR_Multiplier = 1.5; // ATR乗数係数 input int ATR_Period = 7; // ATR期間 // グローバル変数 //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { // インジケーターハンドルの解放 } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { // ポジションがあるか確認 bool hasPosition = false; for(int i = OrdersTotal()-1; i >= 0; i--) { if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) if(OrderSymbol() == Symbol()) { hasPosition = true; TrailStop(OrderTicket(), OrderType()); } } } //+------------------------------------------------------------------+ //| トレーリングストップを実行 | //+------------------------------------------------------------------+ void TrailStop(int ticket, int orderType) { if(!OrderSelect(ticket, SELECT_BY_TICKET)) return; double atr = iATR(NULL, 0, ATR_Period,1); double newStop = 0; double currentStop = OrderStopLoss(); if(orderType == OP_BUY) { newStop = Bid - (atr * ATR_Multiplier); newStop = NormalizeDouble(newStop, Digits); // 現在のストップロスより有利な場合のみ更新 if(newStop > currentStop || currentStop == 0) ModifyStopLoss(ticket, newStop); } else if(orderType == OP_SELL) { newStop = Ask + (atr * ATR_Multiplier); newStop = NormalizeDouble(newStop, Digits); // 現在のストップロスより有利な場合のみ更新 if(newStop < currentStop || currentStop == 0) ModifyStopLoss(ticket, newStop); } } //+------------------------------------------------------------------+ //| ストップロスを変更 | //+------------------------------------------------------------------+ void ModifyStopLoss(int ticket, double newStop) { if(OrderModify(ticket, OrderOpenPrice(), newStop, OrderTakeProfit(), 0, clrRed)) Print("Stop loss updated to ", newStop); else Print("OrderModify failed with error #", GetLastError()); } //+------------------------------------------------------------------+