- Close all positions
- how to close a position
- Automated trading re-creating orders
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());
}
//+------------------------------------------------------------------+
Hello Vladimir,
Thanks for your response, I tried the same with mine code but it is not closing any order.
Mine code is
CTrade trade;
trade.PositionClose(Symbol(), 10);
Print("Error code: ", GetLastError());
}
Also, can it be possible to close order with ticket number as OrderClose.
Hello Vladimir,
Thanks for your response, I tried the same with mine code but it is not closing any order.
Mine code is
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.
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.
- www.mql5.com
Forum on trading, automated trading systems and testing trading strategies
How to Start with Metatrader 5
Simon Gniadkowski, 2013.07.24 10:18
How to post code on this forum . . .
- Please insert your code correctly.
- Do not use "request" - use CTrade class.
Hi Every One.
If i close a sell position while i open sell and buy position. can i declare different object for each ones and call PositionClose(Symbol())
for each one Like that.
//+------------------------------------------------------------------+ //| 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 //-- Here i will open sell order by trades.sell() CTrade trades; //-- Here i will open a buy order by tradeb.buy() CTrade tradeb; //+------------------------------------------------------------------+ //| Script program start function | //+------------------------------------------------------------------+ void OnStart() { //--- сlose a position for the specified symbol tradeb.PositionClose(Symbol()); } //+------------------------------------------------------------------+
Can anyone help me. I have this code but it does not close open poistion
//+------------------------------------------------------------------+
//| StrategyTesterPracticeTrade.mq5 |
//| Copyright 2015, SearchSurf (RmDj) |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2015, SearchSurf (RmDj)"
#property link "https://www.mql5.com"
#property version "1.00"
#property description "This EA is for MT5 and it is mainly used to Practice Trade on Strategy Tester only."
#property description "The manual command is taken from the existance of a text file in the MT5's COMMON/FILE Folder."
#property description "Command text file as follows: 'buy.txt', 'sell.txt', or 'close.txt', only one must appear each time on the folder."
/*
NOTE: (Please read, this is important!!!)
- In order for this EA to use its function on the strategy tester, a textfile command outside MT5's processing is needed for the manual order execution.
- The EA will take the "buy/sell/close" order command mainly on the existance of certain files as "buy.txt", "sell.txt", or "close.txt" at the MT5's COMMON file folder.
(The text file doesn't need anything on it, it's the presence of the filename that matters.)
- Only one file must exist on the said folder at each command, otherwise, the EA will execute the first one it reads and deletes the file/files.
*/
// Global Variables
input double DLot=0.01; // Lot Size:
int Arun_error; // Any error encountered during run
double JustifySize; // Justify lotsize between buy/sell and close
int Ax,Ay,live; // Axis X, Axis Y on graph,live=0 or test=1
double OpenProfit; // Open position profit
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//---
Arun_error=0;
OpenProfit=0;
live=1;
ChartSetInteger(0,CHART_EVENT_MOUSE_MOVE,0,1);
// Profit
ObjectCreate(0,"LABEL1",OBJ_LABEL,0,0,0);
ObjectSetInteger(0,"LABEL1",OBJPROP_XDISTANCE,40);
ObjectSetInteger(0,"LABEL1",OBJPROP_YDISTANCE,102);
ObjectSetInteger(0,"LABEL1",OBJPROP_FONTSIZE,12);
ObjectSetInteger(0,"LABEL1",OBJPROP_COLOR,clrRed);
// Equity
ObjectCreate(0,"LABEL2",OBJ_LABEL,0,0,0);
ObjectSetInteger(0,"LABEL2",OBJPROP_XDISTANCE,40);
ObjectSetInteger(0,"LABEL2",OBJPROP_YDISTANCE,50);
ObjectSetInteger(0,"LABEL2",OBJPROP_FONTSIZE,12);
ObjectSetInteger(0,"LABEL2",OBJPROP_COLOR,clrRed);
ChartRedraw();
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
ObjectDelete(0,"LABEL");
ObjectDelete(0,"LABEL1");
ObjectDelete(0,"LABEL2");
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---
string candle;
double CurP;
JustifySize=DLot;
if(Arun_error>0)
{
Alert("EA detected error: ",Arun_error," -- EA Aborted!!! Pls. close EA now and attend to your open entry/ies.");
Print("EA detected error: ",Arun_error," -- EA Aborted!!! Pls. close EA now and attend to your open entry/ies.");
if(!ObjectFind(0,"LABEL")) ObjectDelete(0,"LABEL");
ObjectCreate(0,"LABEL",OBJ_BUTTON,0,0,0);
ObjectSetInteger(0,"LABEL",OBJPROP_XDISTANCE,270);
ObjectSetInteger(0,"LABEL",OBJPROP_YDISTANCE,40);
ObjectSetInteger(0,"LABEL",OBJPROP_XSIZE,370);
ObjectSetInteger(0,"LABEL",OBJPROP_YSIZE,30);
ObjectSetInteger(0,"LABEL",OBJPROP_FONTSIZE,9);
ObjectSetInteger(0,"LABEL",OBJPROP_COLOR,clrBlack);
ObjectSetInteger(0,"LABEL",OBJPROP_BGCOLOR,clrCyan);
ObjectSetString(0,"LABEL",OBJPROP_TEXT,"Error: EA aborted, please close or restart.");
ChartRedraw();
return;
}
// If there's an open position, display the Profit every tick change.
if(OpenPosition()=="none") OpenProfit=0;
else
{
PositionSelect(_Symbol);
OpenProfit=NormalizeDouble(PositionGetDouble(POSITION_PROFIT),2);
}
ChartTimePriceToXY(0,0,StringToTime(GetBarDetails("time",3,0)),GetBarPrice("close",3,0),Ax,Ay);
ObjectSetInteger(0,"LABEL1",OBJPROP_XDISTANCE,Ax);
ObjectSetInteger(0,"LABEL1",OBJPROP_YDISTANCE,Ay);
ObjectSetString(0,"LABEL1",OBJPROP_TEXT," Profit: "+DoubleToString(OpenProfit,2));
ObjectSetString(0,"LABEL2",OBJPROP_TEXT,"EQUITY: "+DoubleToString(AccountInfoDouble(ACCOUNT_EQUITY),2));
ChartRedraw();
CurP=NormalizeDouble(GetBarPrice("close",3,0),_Digits);
// %%%%%%%%% Below codes will keep checking at every tick for a specific (buy.txt,sell.txt,close.txt) command file at the MT5 Common Folder %%%%%%%%%%%%%%%%%
// If a buy.txt is found at the MT5 COMMON folder, Buy order is executed at default lot size as stated in the input parameter.
if(FileIsExist("buy.txt",FILE_COMMON))
{
FileDelete("sell.txt",FILE_COMMON);
FileDelete("buy.txt",FILE_COMMON);
FileDelete("close.txt",FILE_COMMON);
ExecuteTrade("buy",CurP,JustifySize);
}
// If a sell.txt is found, Sell order is executed at default lot size as stated in the input parameter.
if(FileIsExist("sell.txt",FILE_COMMON))
{
FileDelete("sell.txt",FILE_COMMON);
FileDelete("buy.txt",FILE_COMMON);
FileDelete("close.txt",FILE_COMMON);
ExecuteTrade("sell",CurP,JustifySize);
}
// if a close.txt is found, this will close any open position with the maximum volume size stated on the position.
if(FileIsExist("close.txt",FILE_COMMON))
{
FileDelete("sell.txt",FILE_COMMON);
FileDelete("buy.txt",FILE_COMMON);
FileDelete("close.txt",FILE_COMMON);
if(OpenPosition()=="buy")
{
PositionSelect(_Symbol);
JustifySize=NormalizeDouble(PositionGetDouble(POSITION_VOLUME),2);
ExecuteTrade("sell",CurP,JustifySize);
}
if(OpenPosition()=="sell")
{
PositionSelect(_Symbol);
JustifySize=NormalizeDouble(PositionGetDouble(POSITION_VOLUME),2);
ExecuteTrade("buy",CurP,JustifySize);
}
}
}
//+------------------------------------------------------------------+
//| ChartEvent function |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
//---
if(live==1)
{
// Remarks:
ObjectCreate(0,"LABEL",OBJ_BUTTON,0,0,0);
ObjectSetInteger(0,"LABEL",OBJPROP_XDISTANCE,270);
ObjectSetInteger(0,"LABEL",OBJPROP_YDISTANCE,40);
ObjectSetInteger(0,"LABEL",OBJPROP_XSIZE,370);
ObjectSetInteger(0,"LABEL",OBJPROP_YSIZE,30);
ObjectSetInteger(0,"LABEL",OBJPROP_FONTSIZE,9);
ObjectSetInteger(0,"LABEL",OBJPROP_COLOR,clrBlack);
ObjectSetInteger(0,"LABEL",OBJPROP_BGCOLOR,clrCyan);
ObjectSetString(0,"LABEL",OBJPROP_TEXT,"NOTE: This EA is for Practice Trade on Strategy Tester only!!!");
ChartRedraw();
live=0;
}
}
//+------------------------------------------------------------------+
//| Candle Bar Details |
//+------------------------------------------------------------------+
//entry- (datetime) "time", (long) "tickVOL", (int) "spread", (long) "realVOL", maxbar- number of bars to initiate, bar- at which bar to get details
//entry- (datetime) "lasttime", (ulong) "lastVOL", (long in millisec) "lastupdate", (uint) "TICKflag" === all for latest only...
string GetBarDetails(string entry,int maxbar,int bar) // bars based on the current (present) occurance of point of time.
{
string bardetails;
MqlTick latestP;
MqlRates BarRates[];
ArraySetAsSeries(BarRates,true);
//--- last price quote:
if(!SymbolInfoTick(_Symbol,latestP))
{
Alert("Error getting the latest price quote - error:1002");
Arun_error=1002;
return("error");
}
//--- Get the details of the latest maxbars bars
if(CopyRates(_Symbol,_Period,0,maxbar,BarRates)<0)
{
Alert("Error copying rates/history data - error:1002");
Arun_error=1002;
return("error");
}
if(entry=="time") bardetails=TimeToString(BarRates[bar].time); // datetime
if(entry=="tickVOL") bardetails=IntegerToString(BarRates[bar].tick_volume); // long ...
if(entry=="spread") bardetails=IntegerToString(BarRates[bar].spread); // int
if(entry=="realVOL") bardetails=TimeToString(BarRates[bar].real_volume); // datetime
if(entry=="lasttime") bardetails=TimeToString(latestP.time); // datetime
if(entry=="lastVOL") bardetails=IntegerToString(latestP.volume); // ulong
if(entry=="lastupdate") bardetails=IntegerToString(latestP.time_msc); // long in milliseconds
if(entry=="lastTickflag") bardetails=TimeToString(latestP.flags); // uint
return(bardetails); // ...don't forget to convert the returned string result value to its designated data type.
}
//+------------------------------------------------------------------+
//| Candle Bar Prices |
//+------------------------------------------------------------------+
//entry- open,high,low,close,bid,ask,last, maxbar- number of bars to initiate, bar- at which bar to get price
double GetBarPrice(string price,int maxbar,int bar)
{
double barprice=0;
MqlTick latestP;
MqlRates BarRates[];
ArraySetAsSeries(BarRates,true);
//--- last price quote:
if(!SymbolInfoTick(_Symbol,latestP))
{
Alert("Error getting the latest price quote - error:1003");
Arun_error=1003;
return(0);
}
//--- price details of the latest maxbar bars:
if(CopyRates(_Symbol,_Period,0,maxbar,BarRates)<0)
{
Alert("Error copying rates/history data - error:1003");
Arun_error=1003;
return(0);
}
// for Previous completed bar, where 0-last current one in progress.
if(price=="open") barprice=BarRates[bar].open;
if(price=="close") barprice=BarRates[bar].close; // if bar=0 , its close price is same as current price bid
if(price=="high") barprice=BarRates[bar].high;
if(price=="low") barprice=BarRates[bar].low;
// for Current Bar in Progress:
if(price=="bid") barprice=latestP.bid;
if(price=="ask") barprice=latestP.ask;
if(price=="last") barprice=latestP.last;
return(barprice);
}
//+------------------------------------+
//| Execute TRADE |
//+------------------------------------+
bool ExecuteTrade(string Entry,double ThePrice,double lot) // Entry = buy or sell / returns true if successfull.
{
bool success;
success=true;
MqlTradeRequest mreq; // for trade send request.
MqlTradeResult mresu; // get trade result.
ZeroMemory(mreq); // Initialize trade send request.
Print("Order Initialized");
mreq.action = TRADE_ACTION_DEAL; // immediate order execution
if(Entry=="buy") mreq.price = NormalizeDouble(ThePrice,_Digits); // should be latest bid price
if(Entry=="sell") mreq.price = NormalizeDouble(ThePrice,_Digits); // should be latest ask price
mreq.symbol = _Symbol; // currency pair
mreq.volume = lot; // number of lots to trade
mreq.magic = 11119; // Order Magic Number
if(Entry=="sell") mreq.type = ORDER_TYPE_SELL; // Sell Order
if(Entry=="buy") mreq.type = ORDER_TYPE_BUY; // Buy Order
mreq.type_filling = ORDER_FILLING_FOK; // Order execution type
mreq.deviation=100; // Deviation from current price
//--- send order
if(!OrderSend(mreq,mresu))
{
Alert("Order Not Sent: ",GetLastError());
ResetLastError();
success=false;
}
// Result code
if(mresu.retcode==10009 || mresu.retcode==10008) //Request is completed or order placed
{
if(Entry=="SELL") Print("A Sell order has been successfully placed with Ticket#:",mresu.order,"!!");
if(Entry=="BUY") Print("A Buy order has been successfully placed with Ticket#:",mresu.order,"!!");
}
else
{
Alert("The Order not completed -error:",GetLastError());
ResetLastError();
success=false;
}
if(success==false)
{
Alert("Error ORDER FAILED!!! - error:1004");
Arun_error=1004;
}
return(success);
}
//+------------------------------------+
//| Check if there's an open position |
//+------------------------------------+
string OpenPosition() // Returns "none", "buy", "sell"
{
string post;
post="none";
if(PositionSelect(_Symbol)==true) // open position
{
if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
{
post="buy";
}
else if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
{
post="sell";
}
}
return(post);
}
//+------------------------------------------------------------------+
- www.mql5.com
Can anyone help me. I have this code but it does not close open poistion
...
Forum on trading, automated trading systems and testing trading strategies
When you post code please use the CODE button (Alt-S)!
- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
You agree to website policy and terms of use