Download MetaTrader 5
To add comments, please log in or register
Install apps from the library right in MetaTrader. It is easy!
amber.more
14
amber.more 2016.10.15 23:50 
How to close open position in MQL5? Can You please provide me demo code?
Vladimir Karputov
Moderator
42452
Vladimir Karputov 2016.10.16 08:11  
amber.more:
How to close open position in MQL5? Can You please provide me demo code?

The easiest way is a standard library.

Exampel сlose a position for the specified symbol (used in netting):

//+------------------------------------------------------------------+
//|                                                PositionClose.mq5 |
//|                              Copyright © 2016, Vladimir Karputov |
//|                                           http://wmua.ru/slesar/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2016, Vladimir Karputov"
#property link      "http://wmua.ru/slesar/"
#property version   "1.00"
//--- connection of standard library
#include <Trade\Trade.mqh>
//--- object of class CTrade
CTrade trade;
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//--- сlose a position for the specified symbol
   trade.PositionClose(Symbol());
  }
//+------------------------------------------------------------------+
Files:
amber.more
14
amber.more 2016.10.16 17:10  

Hello Vladimir,

 

Thanks for your response, I tried the same with mine code but it is not closing any order.

Mine code is

void CloseOrders() {

        CTrade trade;

        trade.PositionClose(Symbol(), 10);

        Print("Error code: ", GetLastError());

}

Also, can it be possible to close order with ticket number as OrderClose.

Vladimir Karputov
Moderator
42452
Vladimir Karputov 2016.10.16 18:28  
amber.more:

Hello Vladimir,

 

Thanks for your response, I tried the same with mine code but it is not closing any order.

Mine code is

void CloseOrders() {

        CTrade trade;

        trade.PositionClose(Symbol(), 10);

        Print("Error code: ", GetLastError());

}

Also, can it be possible to close order with ticket number as OrderClose.

It MQL5 - here the order can not be closed. You can only close the position. 

Now, regarding your code, if you have an open position on EURUSD (eg Buy 0.01 EURUSD), then you need to run code in the chart EURUSD. 

 

When you understand this, I will show how to close a position on the ticket number. 

amber.more
14
amber.more 2016.10.16 19:57  
Karputov Vladimir:

It MQL5 - here the order can not be closed. You can only close the position. 

Now, regarding your code, if you have an open position on EURUSD (eg Buy 0.01 EURUSD), then you need to run code in the chart EURUSD. 

 

When you understand this, I will show how to close a position on the ticket number. 

Hey Vladimir,

 

Check my code

//+------------------------------------------------------------------+

//|                                                oscilatorDemo.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\Trade.mqh>

#include <Trade\AccountInfo.mqh>

#include <Trade\PositionInfo.mqh>

#include <Expert\Expert.mqh>

#include <IsNewBar.mqh>

#include <TradeHelp.mqh>


CTrade  Gold_trade;

CAccountInfo accountInfo;

CPositionInfo positionInfo;

CExpert expert;

int     _3d_oscilatorsign = 0, MATrendDetectorHandler = 0, 

        elliottWaveOscillator = 0, iSpectrAnalysisADX = 0;

double _Lots = 0.01;

int _MagicNumber = 1284;


double GetCurrentLot() {


        double temp = _Lots;// * _Factor;

        if(temp > 100) temp = 100;


        return temp;

}


int OnInit()

{

        _3d_oscilatorsign = iCustom(_Symbol, PERIOD_CURRENT, "3d_oscilatorsign", 13, 8, 8, 0.4, 4);

        return(INIT_SUCCEEDED);

}


void OnDeinit(const int reason)

{

        IndicatorRelease(_3d_oscilatorsign);

}


MqlTradeRequest m_request; // request data

MqlTradeResult m_result; // result data

MqlTradeCheckResult m_check_result; // result check data

ulong m_deviation = 10; // deviation default

ENUM_ORDER_TYPE_FILLING m_type_filling;


bool IsStopped(const string function)

{

    if (!IsStopped())

        return (false);

    //--- MQL5 program is stopped

    printf("%s: MQL5 program is stopped. Trading is disabled", function);

    m_result.retcode = TRADE_RETCODE_CLIENT_DISABLES_AT;

    return (true);

}


static bool BUY_Open=false,BUY_Close=true;

static bool SELL_Open=false,SELL_Close=true;


string ResultRetcodeDescription(int retcode)

{

string str;

// ----

switch (retcode)

{

case TRADE_RETCODE_REQUOTE: str = "requotes"; break;

case TRADE_RETCODE_REJECT: str = "Request rejected"; break;

case TRADE_RETCODE_CANCEL: str = "Request canceled by the trader"; break;

case TRADE_RETCODE_PLACED: str = "Order placed"; break;

case TRADE_RETCODE_DONE: str = "application is made"; break;

case TRADE_RETCODE_DONE_PARTIAL: str = "application partially implemented"; break;

case TRADE_RETCODE_ERROR: str = "Request processing error"; break;

case TRADE_RETCODE_TIMEOUT: str = "Request canceled due to the expiration of the time"; break;

case TRADE_RETCODE_INVALID: str = "Invalid request"; break;

case TRADE_RETCODE_INVALID_VOLUME: str = "Wrong amount of the request"; break;

case TRADE_RETCODE_INVALID_PRICE: str = "Wrong price in the request"; break;

case TRADE_RETCODE_INVALID_STOPS: str = "Wrong foot in the request"; break;

case TRADE_RETCODE_TRADE_DISABLED: str = "Trade is disabled"; break;

case TRADE_RETCODE_MARKET_CLOSED: str = "closed market"; break;

case TRADE_RETCODE_NO_MONEY: str = "There is not enough money to make the request"; break;

case TRADE_RETCODE_PRICE_CHANGED: str = "Prices have changed"; break;

case TRADE_RETCODE_PRICE_OFF: str = "There are no quotes to handle the request"; break;

case TRADE_RETCODE_INVALID_EXPIRATION: str = "Invalid expiration date order in the request"; break;

case TRADE_RETCODE_ORDER_CHANGED: str = "Order Status changed"; break;

case TRADE_RETCODE_TOO_MANY_REQUESTS: str = "Too frequent requests"; break;

case TRADE_RETCODE_NO_CHANGES: str = "The query is no change"; break;

case TRADE_RETCODE_SERVER_DISABLES_AT: str = "Autotrading forbidden server"; break;

case TRADE_RETCODE_CLIENT_DISABLES_AT: str = "Auto Trading is prohibited by the client terminal"; break;

case TRADE_RETCODE_LOCKED: str = "The request is blocked for processing"; break;

case TRADE_RETCODE_FROZEN: str = "An order or position are frozen"; break;

case TRADE_RETCODE_INVALID_FILL: str = "Unsupported type of order execution for the balance"; break;

case TRADE_RETCODE_CONNECTION: str = "No connection with the trading server"; break;

case TRADE_RETCODE_ONLY_REAL: str = "The operation is allowed only for real accounts"; break;

case TRADE_RETCODE_LIMIT_ORDERS: str = "Reached limit on the number of pending orders"; break;

case TRADE_RETCODE_LIMIT_VOLUME: str = "There has been a limit on the volume of orders and positions for the symbol"; break;

default: str = "Unknown result";

}

// ----

return (str);

}


void CloseOrders() {

        //Gold_trade.PositionClose(_Symbol, 3);

        //CTrade *trade = new CTrade;

        CTrade trade;

        trade.PositionClose(Symbol(), 10);

        Print("Error code: ", GetLastError());

}


double lastDirection = 0, lastTickDirection = 0;

double Gold_buff[], osi[], mat[], ewo[], isa[];

int totalOrders = 0;


void OnTick()

{

        string name = "3d_oscilatorsign";

        static CIsNewBar NB1;

        static bool Recount1=true;

        CopyBuffer(_3d_oscilatorsign, 0, 0, 1, osi);

        lastTickDirection = osi[0];


        if(NB1.IsNewBar(Symbol(),PERIOD_D1) || Recount1) {

                if(lastTickDirection != 0 && lastDirection != lastTickDirection) {

                        lastDirection = lastTickDirection;


                        MqlTradeRequest request={0};

                        MqlTradeResult  result={0};


                        CloseOrders();


                        if(totalOrders < 100000) {

                                if(osi[0] == 1) {

                                        request.action   = TRADE_ACTION_DEAL;                     // type of trade operation

                                        request.symbol   = Symbol();                              // symbol

                                        request.volume   = GetCurrentLot();                             // volume of 0.1 lot

                                        request.type     = ORDER_TYPE_BUY;                   // order type

                                        request.price    = SymbolInfoDouble(Symbol(),SYMBOL_ASK); // price for opening

                                        request.deviation= 5;                                     // allowed deviation from the price

                                        request.magic    = _MagicNumber;

                                        if(!OrderSend(request, result)) {

                                                PrintFormat("OrderSend error %d", GetLastError());

                                        }

                                        else {

                                                totalOrders++;

                                        }

                                }

                                else if(osi[0] == -1) {

                                        request.action   = TRADE_ACTION_DEAL;                     // type of trade operation

                                        request.symbol   = Symbol();                              // symbol

                                        request.volume   = GetCurrentLot();                             // volume of 0.1 lot

                                        request.type     = ORDER_TYPE_SELL;                   // order type

                                        request.price    = SymbolInfoDouble(Symbol(),SYMBOL_BID); // price for opening

                                        request.deviation= 5;                                     // allowed deviation from the price

                                        request.magic    = _MagicNumber;

                                        if(!OrderSend(request, result)) {

                                                PrintFormat("OrderSend error %d", GetLastError());

                                        }  

                                        else {

                                                totalOrders++;

                                        }                                    

                                }

                        }

                }

        }

}

 

Running this on USDJPY but no luck while closing position. 

Automated Trading and Strategy Testing
Automated Trading and Strategy Testing
  • www.mql5.com
MQL5: language of trade strategies built-in the MetaTrader 5 Trading Platform, allows writing your own trading robots, technical indicators, scripts and libraries of functions
Sergey Golubev
Moderator
54552
Sergey Golubev 2016.10.16 20:35  
Vladimir Karputov
Moderator
42452
Vladimir Karputov 2016.10.16 20:47  
amber.more:


  1. Please insert your code correctly.
  2. Do not use "request" - use CTrade class.

/
To add comments, please log in or register