Hi everyone, I am new learner. I want to improve my coding skill so I code everything come into my mind.
Today, I want to code an EA with following function:
- Place order with TP = 20pip, SL = 10pip. *done.
- Everytime SL hit, it will open opposite order which martingale Lotsize with TP =20pip, SL = 10pip.
*To do that, I will place a pending order at first SL, and delete it if TP hit. This order will have lotsize*multiplier and tp 20pip, sl 10pip.*
I am not sure how to know when to delete order if TP hit. To do that, I check the order history, if latest order has profit >0, then i will delete the pending order. *not sure about that...I need your advise *.
Sometimes I got an error that EA place and order and delete it after that. It's not happen all the times but sometimes, I dont know why.
Below is my whole code. Everyone free to point out my mistake. I am appreciated about that.
Have a good one.
Will
Today, I want to code an EA with following function:
- Place order with TP = 20pip, SL = 10pip. *done.
- Everytime SL hit, it will open opposite order which martingale Lotsize with TP =20pip, SL = 10pip.
*To do that, I will place a pending order at first SL, and delete it if TP hit. This order will have lotsize*multiplier and tp 20pip, sl 10pip.*
I am not sure how to know when to delete order if TP hit. To do that, I check the order history, if latest order has profit >0, then i will delete the pending order. *not sure about that...I need your advise *.
Sometimes I got an error that EA place and order and delete it after that. It's not happen all the times but sometimes, I dont know why.
Below is my whole code. Everyone free to point out my mistake. I am appreciated about that.
Have a good one.
Will
Inserted Code
//+------------------------------------------------------------------+ //| My Test EA .mq4 | //| MQL4 tutorial on quivofx.com | //| | //+------------------------------------------------------------------+ #property copyright "" #property link "" #property version "4.00" #property strict //--- input parameters extern bool Auto_trade = false; input int TakeProfit=20; input int StopLoss=10; input double FirstLot=0.1; input double Lot_Multiplier = 2; input int Slippage=3; input int MagicNumber=5555; input double Profit_target= 20; //--- global variables double MyPoint; int MySlippage; //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { //--- MyPoint = MyPoint(); MySlippage = MySlippage(); //--- return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { //--- } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { //--- Comment(StringFormat("Show info\nnext_lot = %G\nprofit_Am = %G", NormalizeDouble(next_lot,2), NormalizeDouble(profit_bracket,2))); if(TotalOpenOrders() == 0 && IsNewBar() == true) { // Check Buy Entry if(BuySignal() == true && Auto_trade == true) { OpenBuy(); } // Check Sell Entry else if(SellSignal() == true && Auto_trade == true) { OpenSell(); } } ProfitEachOrder(); if(TotalPendingOrders()>0) { delete_pending(); } } //+------------------------------------------------------------------+ //| Custom functions | //+------------------------------------------------------------------+ // Initialize Indicators // Buy Logic bool BuySignal() { if(Open[2] > Close[2] && Open[1] < Close[1] && High[2] < High[1] && // Buy and sell logic base on Engulfing strategy Low[2] > Low[1] && Close[1]> Open[2]) { return(true); } else { return(false); } } // Sell Logic bool SellSignal() { if(Open[2] < Close[2] && Open[1] > Close[1] && High[2] < High[1] && Low[2] > Low[1] && Close[1]< Open[2]) { return(true); } else { return(false); } } // Open Buy Order void OpenBuy() { // Open Buy Order int ticket = OrderSend(_Symbol,OP_BUY,FirstLot,Ask,MySlippage,0,0,"BUY",MagicNumber); if(ticket<0) { Print("OrderSend failed with error #",GetLastError()); } else { Print("OrderSend placed successfully"); } // Modify Buy Order bool res = OrderModify(ticket,OrderOpenPrice(),Ask-StopLoss*MyPoint,Ask+TakeProfit*MyPoint,0); if(!res) { Print("Error in OrderModify. Error code=",GetLastError()); } else { Print("Order modified successfully."); } } // Open Sell Order void OpenSell() { //Open Sell Order int ticket = OrderSend(_Symbol,OP_SELL,FirstLot,Bid,MySlippage,0,0,"SELL",MagicNumber); if(ticket<0) { Print("OrderSend failed with error #",GetLastError()); } else { Print("OrderSend placed successfully"); } // Modify Sell Order bool res = OrderModify(ticket,OrderOpenPrice(),Bid+StopLoss*MyPoint,Bid-TakeProfit*MyPoint,0); if(!res) { Print("Error in OrderModify. Error code=",GetLastError()); } else { Print("Order modified successfully."); } } // Get My Points for 3 digits broker or 5 digits broker. double MyPoint() { double CalcPoint = 0; if(_Digits == 2 || _Digits == 3) CalcPoint = 0.01; else if(_Digits == 4 || _Digits == 5) CalcPoint = 0.0001; return(CalcPoint); } // Get My Slippage int MySlippage() { int CalcSlippage = 0; if(_Digits == 2 || _Digits == 4) CalcSlippage = Slippage; else if(_Digits == 3 || _Digits == 5) CalcSlippage = Slippage * 10; return(CalcSlippage); } // Check if there is a new bar bool IsNewBar() { static datetime RegBarTime=0; datetime ThisBarTime = Time[0]; if (ThisBarTime == RegBarTime) { return(false); } else { RegBarTime = ThisBarTime; return(true); } } // Returns the number of total open orders for this Symbol and MagicNumber int TotalOpenOrders() { int total_orders = 0; for(int order = 0; order < OrdersTotal(); order++) { if(OrderSelect(order,SELECT_BY_POS,MODE_TRADES)==false) break; if(OrderSymbol() == _Symbol) { total_orders++; } } return(total_orders); } //----Martingale----// double next_lot = 0.0; double profit_bracket=0; int PendingTicket=0; void ProfitEachOrder(){ double profit_total=0; for(int i=OrdersHistoryTotal()-1; i >= 0; i--) { if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)){ //check history string ordSym=OrderSymbol(); int ordType=OrderType(); datetime ordTime=OrderOpenTime(); double ordLot=OrderLots(); double ordOp=OrderOpenPrice(); int ordMag=OrderMagicNumber(); int ordTicket=OrderTicket(); double ordProfit=OrderProfit(); if(ordSym==Symbol() && ordProfit <0){ profit_total+=OrderProfit();} // find all sum of order profit <0 Print("profit history total "+DoubleToString(profit_total,2)); // PERFECT DISPLAY } } /* // calculate next lot double spread = MarketInfo(_Symbol,MODE_SPREAD); double tickvalue = MarketInfo(_Symbol,MODE_TICKVALUE); //--Dont need to care about this section double ticksize = MarketInfo(_Symbol,MODE_TICKSIZE); RefreshRates(); next_lot = (Profit_target + MathAbs(profit_total))*tickvalue/(TakeProfit); next_lot = NormalizeDouble(next_lot,2); */ //--PLACE HEDGE ORDER--/ double lastSL =0.0, lastProfit=0.0, lastLot=0.0; int lastType=0; datetime lastTime =0; int PendingType =0; double PendingPrice =0.0; double PendingLot = 0.0; for(int i=OrdersTotal()-1; i >= 0; i--) { if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){ string ordSym=OrderSymbol(); int ordType=OrderType(); datetime ordTime=OrderOpenTime(); double ordLot=OrderLots(); double ordOp=OrderOpenPrice(); int ordMag=OrderMagicNumber(); int ordTicket=OrderTicket(); double ordProfit=OrderProfit(); double ordTp=OrderTakeProfit(); double ordSL=OrderStopLoss(); if(ordSym==Symbol() && ordTime>lastTime && OrderType()<=1) //get last order SL, Type, Lot { lastTime=ordTime; lastSL = ordSL; lastType = ordType; lastLot = ordLot; } //----Get pending ticket ----// if(ordSym==Symbol() && OrderType()>=4){ // get pending order SL, Type, Lot, Ticket PendingType=ordType; PendingPrice=ordOp; PendingLot=ordLot; PendingTicket=ordTicket; } Print("PendingPrice "+DoubleToString(PendingPrice,Digits)); Print("PendingLot "+DoubleToString(PendingLot,2)); Print("PendingType "+IntegerToString(PendingType,0)); Print("PendingTicket "+IntegerToString(PendingTicket,0)); //Calculate martingale lot next_lot = lastLot * Lot_Multiplier; // Calculate Lotsize for next order. next_lot = NormalizeDouble(next_lot,2); RefreshRates(); if(lastType == OP_BUY && TotalPendingOrders()==0) // place Sell stop order at SL of previous order, { if(!OrderSend(_Symbol,OP_SELLSTOP,next_lot,ordSL,Slippage,ordSL+StopLoss*MyPoint,ordSL-TakeProfit*MyPoint,"SELLSTOP",0)) Print("Order SELLSTOP Failed! Error# "+IntegerToString(GetLastError())); } if(lastType == OP_SELL && TotalPendingOrders()==0) // place Buy stop order at SL of previous order, { if(!OrderSend(_Symbol,OP_BUYSTOP,next_lot,ordSL,Slippage,ordSL-StopLoss*MyPoint,ordSL+TakeProfit*MyPoint,"BUYSTOP",0)) Print("Order BUYSTOP Failed! Error# "+IntegerToString(GetLastError())); } } } } //Get total Pending order int TotalPendingOrders(){ int total=0; for(int i=OrdersTotal()-1; i >= 0; i--) { if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){ string ordsymB = OrderSymbol(); int ordtypeB =OrderType(); if(ordsymB==Symbol() && ordtypeB>=4){ total++; } } } return (total); } //---Delete the pending order if TP hit.---// void delete_pending() { datetime CurrTime =TimeCurrent(); for(int h=OrdersHistoryTotal()-1; h >= 0; h--) { if(OrderSelect(h,SELECT_BY_POS,MODE_HISTORY)){ // H stand for History. string HSym=OrderSymbol(); int HType=OrderType(); datetime HTime=OrderCloseTime(); double HLot=OrderLots(); double HOp=OrderOpenPrice(); int HMag=OrderMagicNumber(); int HTicket=OrderTicket(); double HProfit=OrderProfit(); if(HProfit > 0 && HTime==CurrTime ) { RefreshRates(); if(!OrderDelete(PendingTicket)) Print("OrderDelete Pending Failed! Error# "+IntegerToString(GetLastError())); break;} } } } /* Dat hedge order ok delete order ok calculate volume !OK */