how to close a position - page 2

 
Vladimir Karputov:


Script "CloseAllPositions" -  example class CTrade, method PositionClose (Closes a position with the specified ticket):

Thanks! This worked!
 

Kusmayadi


void OnTick()

  {

  

   string signal="";



  double KArray[];

  double KArray[];

   

  

  ArraySetAsSeries(KArray,true);

  ArraySetAsSeries(DArray,true);

  

  

  int StochasticDefinition=iStochastic(_Symbol,_Period,14,3,3 MODE_SMA,STO_LOWHIGH);

  

  

  CopyBuffer(StochasticDefinition,0,0,3,KArray);

  CopyBuffer(StochasticDefinition,1,0,3,DArray);

  

  

  double KValue0=KArray[0];

  double KValue0=KArray[0];

  

  

  double KValue0=KArray[1];

  double KValue0=KArray[1];

  

  

  

  

  if (KValue0<20&&DValue<20)

  

     if ((KValue0>DValue0<20) && (KValue1<DValue1))

       {

         signal="buy";

         

  

  

  

  

   if (KValue0>80&&DValue>80)

   

   

   ((KValue0>80&&DValue>80) && (KValue1>DVlue1))

    {

       signal="sell";

    }

    

    //Chart output

    Comment ("Signal: ",signal);

    

       }

 

thank you for this code ,

it look work , but how to avoid rejected ??


2019.05.31 10:59:16.731 testClose (EURUSD_,H1) CTrade::OrderSend: instant buy 0.01 position #49458 EURUSD_ at 1.11356 [rejected]



//+------------------------------------------------------------------+
//|                                            CloseAllPositions.mq5 |
//|                        Copyright 2016, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2016, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
CPositionInfo  m_position;                   // trade position object
CTrade         m_trade;                      // trading object
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   for(int i=PositionsTotal()-1;i>=0;i--) // returns the number of current position
      if(m_position.SelectByIndex(i))     // selects the position by index for further access to its properties
         if(m_position.Symbol()==Symbol())
            m_trade.PositionClose(m_position.Ticket()); // close a position by the specified symbol
  }
//+------------------------------------------------------------------+
Files:
rejected.gif  36 kb
 
陳柏昌:

thank you for this code ,

it look work , but how to avoid rejected ??


2019.05.31 10:59:16.731 testClose (EURUSD_,H1) CTrade::OrderSend: instant buy 0.01 position #49458 EURUSD_ at 1.11356 [rejected]

m_trade.PositionClose(m_position.Ticket(), 100); // close a position by the specified symbol

https://www.mql5.com/en/docs/standardlibrary/tradeclasses/ctrade/ctradesetdeviationinpoints

Documentation on MQL5: Standard Library / Trade Classes / CTrade / SetDeviationInPoints
Documentation on MQL5: Standard Library / Trade Classes / CTrade / SetDeviationInPoints
  • www.mql5.com
Standard Library / Trade Classes / CTrade / SetDeviationInPoints - Reference on algorithmic/automated trading language for MetaTrader 5
 

PositionClose(PositionGetSymbol(i),0.1))  add 0.1=deviation 

try it!

 
Hello great contribution.

How to make all positions close at one o'clock 23:00
 
rblazquezra :
Hello great contribution.

How to make all positions close at one o'clock 23:00

Example: Close on time . One clarification - the EA works only with the current symbol and the specified Magic number. If you want to close all-all positions, just comment out the lines with the symbol filter and Magic number.

Close on time
Close on time
  • www.mql5.com
Советник закрывает позиции и удаляет отложенные ордера в определённое время. Сам принцип работы: на закрытие и удаление даётся десять минут от начала времени Close Time. Если удастся уложится в задание раньше десяти минут - значит советник прекратит в этот день поиск задания раньше. Переменная  Close Time, хотя и задаётся в полном формате, но...
 

hi, Can anyone check what is going wrong with the closing of the positions here? This is the code I written , its not working.


#include <Trade\Trade.mqh>
//include the C trade module
CTrade trade;
void OnTick()
  {
  double Ask=NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits); 
  double Bid=NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);
  double Balance=AccountInfoDouble(ACCOUNT_BALANCE);
  double Equity=AccountInfoDouble(ACCOUNT_EQUITY);
  string signal="";
  double RSIarray[];
  ArraySetAsSeries(RSIarray,true);
  int RSIvalue = iRSI(NULL,PERIOD_D1,14,PRICE_CLOSE);
  CopyBuffer (RSIvalue,0,0,3,RSIarray);
  if (RSIvalue>60) signal="BUY";
  if (RSIvalue<40) signal="SELL";
  if (signal=="SELL" && PositionsTotal()<1)
  trade.Sell(0.10,NULL,Bid,0,0,NULL);
  if (signal=="BUY" && PositionsTotal()<1)
  trade.Buy(0.10,NULL,Ask,0,0,NULL);
  Comment ("The Current Signal is :",signal);
  ///// condition for close.
  if (Equity > Balance)
   {
CloseAllPosition();
   }
  }
void CloseAllPosition()
   {
for (int i=PositionsTotal()-1; i>=0 ; i--)
      {
      int ticket=PositionGetTicket(i);
      trade.PositionClose(i);
      }
   }
//+------------------------------------------------------------------+


Documentation on MQL5: Constants, Enumerations and Structures / Environment State / Account Properties
Documentation on MQL5: Constants, Enumerations and Structures / Environment State / Account Properties
  • www.mql5.com
, then each symbol positions will be closed in the same order, in which they are opened, starting with the oldest one. In case of an attempt to close positions in a different order, the trader will receive an appropriate error. There are several types of accounts that can be opened on a trade server. The type of account on which an MQL5 program...
 
tush1822 :

hi, Can anyone check what is going wrong with the closing of the positions here? This is the code I written , its not working.



Mistake number 1: the indicator handle SHOULD BE CREATED ONLY ONCE - it should be done in OnInit () !!!

Please correct this error first. Then you can look further.

 

Hi Vladimir,

I am having the same problem, my code doesnt work.

CTrade Pool;
/////
void ClosePositions()   // Take profits by RSI signals
     {
      for(int i=0; i<PositionsTotal(); i++)
      if(PositionSelectByTicket(PositionGetTicket(i)))
             
         if(PositionGetString(POSITION_SYMBOL)==Symbol())
          if(PositionGetInteger(POSITION_MAGIC)==MagicNumber)
          //  if(PositionGetDouble(POSITION_PROFIT)>0)  
             if(CloseBySignal)  //Bool in Settings 
             {
               if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)                                
                 if(RSI_tpLong())    // RSI signal (tested, works)
                   
                Pool.PositionClose(PositionGetTicket(i)); 
Update: Above code works, function was never called.  I have also on issue with the PCSv9. If someone knows PCSv9 I would like to hire her/him.
The Fundamentals of Testing in MetaTrader 5
The Fundamentals of Testing in MetaTrader 5
  • www.mql5.com
The idea of ​​automated trading is appealing by the fact that the trading robot can work non-stop for 24 hours a day, seven days a week. The robot does not get tired, doubtful or scared, it's is totally free from any psychological problems. It is sufficient enough to clearly formalize the trading rules and implement them in the algorithms, and...