Orders Execution
0
Views
0
Downloads
0
Favorites
hma_power2.02
//+-----------------------------------------------------------------------------------+
//| HMA POWER EA 3.mq4 |
//| Copyright © 2005, Alejandro Galindo |
//| http://elCactus.com |
//| Copyright © 2007, AZAM575 & OILFXPRO & YUSOF786 |
//| http://mymefx.com |
//+-----------------------------------------------------------------------------------+
///Please, do not sell this EA because its FREE
#property copyright "Copyright © 2007, AZAM575&OILFXPRO&YUSOF786"
#property link "MYMEFX.COM"
extern string INFO="HMA POWER EA";
extern string OWN="Copyright © 2007, AZAM575&OILFXPRO&YUSOF786";
extern int last_bar= 1;
extern bool long = true;
extern bool short = true;
extern bool ExitWithRSI=False;
extern string sb="--TRADE SETTING--";
extern double Lots = 0.1; // We start with this lots number
extern int TakeProfit = 32; // Profit Goal for the latest order opened
extern double multiply=2.0;
extern int MaxTrades=15; // Maximum number of orders to open
extern int Pips=22; // Distance in Pips from one order to another
extern int StopLoss = 0; // StopLoss
extern int TrailingStop = 0;// Pips to trail the StopLoss
extern string MM="--MOney Management--"; // (from order 2, not from first order
extern string MMSwicth="if one the lots size will increase based on account size";
extern int mm=0; // if one the lots size will increase based on account size
extern string riskset="risk to calculate the lots size (only if mm is enabled)";
extern int risk=1; // risk to calculate the lots size (only if mm is enabled)
extern string accounttypes="0 if Normal Lots, 1 for mini lots, 2 for micro lots";
extern int AccountType=1; // 0 if Normal Lots, 1 for mini lots, 2 for micro lots
extern string magicnumber="--MAgic No--";
extern int MagicNumber=222777; // Magic number for the orders placed
//extern int MagicNumber=0; // Magic number for the orders placed
extern string so="--CUTLOSS SETTING--";
extern bool MyMoneyProfitTarget=False;
extern double My_Money_Profit_Target=50;
extern bool SecureProfitProtection=False;
extern string SP="If profit made is bigger than SecureProfit we close the orders";
extern int SecureProfit=20; // If profit made is bigger than SecureProfit we close the orders
extern string OTP="Number of orders to enable the account protection";
extern int OrderstoProtect=3; // Number of orders to enable the account protection
extern string ASP="if one will check profit from all symbols, if cero only this symbol";
extern bool AllSymbolsProtect=False; // if one will check profit from all symbols, if cero only this symbol
extern string EP="if true, then the expert will protect the account equity to the percent specified";
extern bool EquityProtection=False; // if true, then the expert will protect the account equity to the percent specified
extern string AEP="percent of the account to protect on a set of trades";
extern int AccountEquityPercentProtection=90; // percent of the account to protect on a set of trades
extern string AMP="if true, then the expert will use money protection to the USD specified";
extern bool AccountMoneyProtection=False;
extern double AccountMoneyProtectionValue=3000.00;
string s1="--seting berapa jam dia nak open order--";
bool UseHourTrade = False;
int FromHourTrade = 0;
int ToHourTrade = 1;
extern string TradingTime="--trading time setting--";
extern bool UseTradingHours = false;
extern bool TradeAsianMarket = true;
extern int StartHour1 = 0; // Start trades after time
extern int StopHour1 = 3; // Stop trading after time
extern bool TradeEuropeanMarket = true;
extern int StartHour2 = 9; // Start trades after time
extern int StopHour2 = 11; // Stop trading after time
extern bool TradeNewYorkMarket = false;
extern int StartHour3 = 15; // Start trades after time
extern int StopHour3 = 17; // Stop trading after time
extern bool TradeOnFriday=True;
extern string OtherSetting="--Others Setting--";
int OrdersTimeAlive=0; // in seconds
extern string reverse="if one the desition to go long/short will be reversed";
extern bool ReverseCondition=False; // if one the desition to go long/short will be reversed
extern string limitorder="if true, instead open market orders it will open limit orders ";
extern bool SetLimitOrders=False; // if true, instead open market orders it will open limit orders
int Manual=0; // If set to one then it will not open trades automatically
color ArrowsColor=Black; // color for the orders arrows
int OpenOrdersBasedOn=16; // Method to decide if we start long or short
bool ContinueOpening=True;
int OpenOrders=0, cnt=0;
int MarketOpenOrders=0, LimitOpenOrders=0;
int slippage=5;
double sl=0, tp=0;
double BuyPrice=0, SellPrice=0;
double lotsi=0, mylotsi=0;
int mode=0, myOrderType=0, myOrderTypetmp=0;
double LastPrice=0;
int PreviousOpenOrders=0;
double Profit=0;
int LastTicket=0, LastType=0;
double LastClosePrice=0, LastLots=0;
double Pivot=0;
double PipValue=0;
bool Reversed=False;
double tmp=0;
double iTmpH=0;
double iTmpL=0;
datetime NonTradingTime[][2];
bool FileReaded=false;
string dateLimit = "2030.01.12 23:00";
int CurTimeOpeningFlag=0;
datetime LastOrderOpenTime=0;
bool YesStop;
// Orest : new variables declaration
extern string HedgeSettings="-- Hedging safety strategy settings --";
extern bool Use_Hedging = false;
extern int Max_Loss_For_Hedge_pips = 50; //After how many negative pips the hedge is trigered
//extern int Max_Days_Hedge_Open = 0;
extern double Hedge_Lots_Multiplier = 1.0;
extern int Pips_Less_Then_Max_Closing = 10;
datetime LastHedgeAction;
int Max_SL_pips = 500;
// end of new variables declaration
//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init()
{
//----
// Orest
LastHedgeAction=0;
if (Hedge_Lots_Multiplier < 1)
Hedge_Lots_Multiplier = 1;
//----
return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----
DeleteAllObjects();
//----
return(0);
}
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
//----
int cnt=0;
bool result;
string text="";
string version="VERSI INI DAH EXPIRED...SILA YM xxul_gunturean utk penggantian";
//***==============================
// Orest -- Process hedging orders
int loss_pips_start = 0;
if (Use_Hedging)
hedgeManager();
//***==============================
// skrip masa trading
if (UseTradingHours)
{
YesStop = true;
// Check trading Asian Market
if (TradeAsianMarket)
{
if (StartHour1 > 18)
{
// Check broker that uses Asian open before 0:00
if (Hour() >= StartHour1) YesStop = false;
if (!YesStop)
{
if (StopHour1 < 24)
{
if ( Hour() <= StopHour1) YesStop = false;
}
// These cannot be combined even though the code looks the same
if (StopHour1 >=0)
{
if ( Hour() <= StopHour1) YesStop = false;
}
}
}
else
{
if (Hour() >= StartHour1 && Hour() <= StopHour1) YesStop = false;
}
}
if (YesStop)
{
// Check trading European Market
if (TradeEuropeanMarket)
{
if (Hour() >= StartHour2 && Hour() <= StopHour2) YesStop = false;
}
}
if (YesStop)
{
// Check trading European Market
if (TradeNewYorkMarket)
{
if (Hour() >= StartHour3 && Hour() <= StopHour3) YesStop = false;
}
}
if (YesStop)
{
// Comment ("Trading has been stopped as requested - wrong time of day");
return (0);
}
}
// skrip masa trading
if (AccountType==0)
{
if (mm!=0) { lotsi=MathCeil(AccountBalance()*risk/10000); }
else { lotsi=Lots; }
}
if (AccountType==1)
{ // then is mini
if (mm!=0) { lotsi=MathCeil(AccountBalance()*risk/10000)/10; }
else { lotsi=Lots; }
}
if (AccountType==2)
{
if (mm!=0) { lotsi=MathCeil(AccountBalance()*risk/10000)/100; }
else { lotsi=Lots; }
}
if (lotsi<0.01) lotsi=0.01;
if (lotsi>100) lotsi=100;
OpenOrders=0;
MarketOpenOrders=0;
LimitOpenOrders=0;
for(cnt=0;cnt<OrdersTotal();cnt++)
{
if (OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
{
if (OrderSymbol()==Symbol() && OrderMagicNumber() == MagicNumber)
{
if (OrderType()==OP_BUY || OrderType()==OP_SELL)
{
MarketOpenOrders++;
LastOrderOpenTime=OrderOpenTime();
}
if (OrderType()==OP_SELLLIMIT || OrderType()==OP_BUYLIMIT) LimitOpenOrders++;
OpenOrders++;
}
}
}
if (OpenOrders<1)
{
if (!TradeOnFriday && DayOfWeek()==5)
{
Comment("TradeOnfriday is False");
return(0);
}
}
PipValue=MarketInfo(Symbol(),MODE_TICKVALUE);
if (PipValue==0) { PipValue=5; }
if (AccountMoneyProtection && AccountBalance()-AccountEquity()>=AccountMoneyProtectionValue)
{
text = text + "\nClosing all orders and stop trading because account money protection activated..";
Print("Closing all orders and stop trading because account money protection activated.. Balance: ",AccountBalance()," Equity: ",AccountEquity());
PreviousOpenOrders=OpenOrders+1;
ContinueOpening=False;
return(0);
}
////aku masukkan time
if (UseHourTrade){
if (!(Hour()>=FromHourTrade && Hour()<=ToHourTrade)) {
text = text + "\nORDER TELAH DI TUTUP KERANA MASA DAH TAMAT.";
Print("ORDER TELAH DI TUTUP KERANA MASA TAMAT. UNTUNG: ",AccountProfit()," EKUITI: ",AccountEquity());
PreviousOpenOrders=OpenOrders+1;
ContinueOpening=False;
return(0);
}
}
//set my profit for one Day
if (MyMoneyProfitTarget && AccountProfit()>= My_Money_Profit_Target)
{
text = text + "\nClosing all orders and stop trading because mymoney profit target reached..";
Print("Closing all orders and stop trading because mymoney profit target reached.. Profit: ",AccountProfit()," Equity: ",AccountEquity());
PreviousOpenOrders=OpenOrders+1;
ContinueOpening=False;
return(0);
}
// Account equity protection
if (EquityProtection && AccountEquity()<=AccountBalance()*AccountEquityPercentProtection/100)
{
text = text + "\nClosing all orders and stop trading because account money protection activated.";
Print("Closing all orders and stop trading because account money protection activated. Balance: ",AccountBalance()," Equity: ", AccountEquity());
//Comment("Closing orders because account equity protection was triggered. Balance: ",AccountBalance()," Equity: ", AccountEquity());
//OrderClose(LastTicket,LastLots,LastClosePrice,slippage,Orange);
PreviousOpenOrders=OpenOrders+1;
ContinueOpening=False;
return(0);
}
// if dont trade at fridays then we close all
if (!TradeOnFriday && DayOfWeek()==5)
{
PreviousOpenOrders=OpenOrders+1;
ContinueOpening=False;
text = text +"\nClosing all orders and stop trading because TradeOnFriday protection.";
Print("Closing all orders and stop trading because TradeOnFriday protection.");
}
// Orders Time alive protection
if (OrdersTimeAlive>0 && CurTime() - LastOrderOpenTime>OrdersTimeAlive)
{
PreviousOpenOrders=OpenOrders+1;
ContinueOpening=False;
text = text + "\nClosing all orders because OrdersTimeAlive protection.";
Print("Closing all orders because OrdersTimeAlive protection.");
}
if (PreviousOpenOrders>OpenOrders)
{
for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
{
if (OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
{
mode=OrderType();
if ((OrderSymbol()==Symbol() && OrderMagicNumber() == MagicNumber) || AllSymbolsProtect)
{
if (mode==OP_BUY || mode==OP_SELL)
{
OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),slippage,ArrowsColor);
return(0);
}
}
}
}
for(cnt=0; cnt<OrdersTotal(); cnt++)
{
if (OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
{
mode=OrderType();
if ((OrderSymbol()==Symbol() && OrderMagicNumber() == MagicNumber) || AllSymbolsProtect)
{
if (mode==OP_SELLLIMIT || mode==OP_BUYLIMIT || mode==OP_BUYSTOP || mode==OP_SELLSTOP)
{
OrderDelete(OrderTicket());
return(0);
}
}
}
}
}
PreviousOpenOrders=OpenOrders;
if (OpenOrders>=MaxTrades)
{
ContinueOpening=False;
} else {
ContinueOpening=True;
}
if (LastPrice==0)
{
for(cnt=0;cnt<OrdersTotal();cnt++)
{
if (OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
{
mode=OrderType();
if (OrderSymbol()==Symbol() && OrderMagicNumber() == MagicNumber)
{
LastPrice=OrderOpenPrice();
if (mode==OP_BUY) { myOrderType=2; }
if (mode==OP_SELL) { myOrderType=1; }
}
}
}
}
// SecureProfit protection
//if (SecureProfitProtection && MarketOpenOrders>=(MaxTrades-OrderstoProtect)
// Modified to make easy to understand
if (SecureProfitProtection && MarketOpenOrders>=OrderstoProtect)
{
Profit=0;
for(cnt=0;cnt<OrdersTotal();cnt++)
{
if (OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
{
// Orest
if ((OrderSymbol()==Symbol() && (OrderMagicNumber()==MagicNumber ||
OrderMagicNumber()==MagicNumber+1 || OrderMagicNumber()==MagicNumber+2)) || AllSymbolsProtect)
Profit=Profit+OrderProfit();
}
}
if (Profit>=SecureProfit)
{
text = text + "\nClosing orders because account protection with SecureProfit was triggered.";
Print("Closing orders because account protection with SeureProfit was triggered. Balance: ",AccountBalance()," Equity: ", AccountEquity()," Profit: ",Profit);
PreviousOpenOrders=OpenOrders+1;
ContinueOpening=False;
return(0);
}
}
myOrderTypetmp=3;
switch (OpenOrdersBasedOn)
{
case 16:
myOrderTypetmp=OpenOrdersBasedOnRSI();
break;
default:
myOrderTypetmp=OpenOrdersBasedOnRSI();
break;
}
if (OpenOrders<1 && Manual==0)
{
myOrderType=myOrderTypetmp;
if (ReverseCondition)
{
if (myOrderType==1) { myOrderType=2; }
else { if (myOrderType==2) { myOrderType=1; } }
}
}
if (ReverseCondition)
{
if (myOrderTypetmp==1) { myOrderTypetmp=2; }
else { if (myOrderTypetmp==2) { myOrderTypetmp=1; } }
}
// if we have opened positions we take care of them
cnt=OrdersTotal()-1;
while(cnt>=0)
{
if(OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES)==false) break;
if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber) // && Reversed==False)
{
//Print("Ticket ",OrderTicket()," modified.");
// Orest
loss_pips_start = getPipsForSL(OrderOpenPrice(),OrderStopLoss(), OrderType());
if (OrderType()==OP_SELL && loss_pips_start < Max_SL_pips)
{
if (ExitWithRSI&& myOrderTypetmp==2)
{
PreviousOpenOrders=OpenOrders+1;
ContinueOpening=False;
text = text +"\nClosing all orders because Indicator triggered another signal.";
Print("Closing all orders because Indicator triggered another signal.");
//return(0);
}
if (TrailingStop>0)
{
if ((OrderOpenPrice()-OrderClosePrice())>=(TrailingStop*Point+Pips*Point))
{
if (OrderStopLoss()>(OrderClosePrice()+TrailingStop*Point))
{
result=OrderModify(OrderTicket(),OrderOpenPrice(),OrderClosePrice()+TrailingStop*Point,OrderClosePrice()-TakeProfit*Point-TrailingStop*Point,0,Purple);
if(result!=TRUE) Print("LastError = ", GetLastError());
else OrderPrint();
return(0);
}
}
}
}
if (OrderType()==OP_BUY && loss_pips_start < Max_SL_pips)
{
if (ExitWithRSI && myOrderTypetmp==1)
{
PreviousOpenOrders=OpenOrders+1;
ContinueOpening=False;
text = text +"\nClosing all orders because Indicator triggered another signal.";
Print("Closing all orders because Indicator triggered another signal.");
//return(0);
}
if (TrailingStop>0)
{
if ((OrderClosePrice()-OrderOpenPrice())>=(TrailingStop*Point+Pips*Point))
{
if (OrderStopLoss()<(OrderClosePrice()-TrailingStop*Point))
{
result=OrderModify(OrderTicket(),OrderOpenPrice(),OrderClosePrice()-TrailingStop*Point,OrderClosePrice()+TakeProfit*Point+TrailingStop*Point,0,ArrowsColor);
if(result!=TRUE) Print("LastError = ", GetLastError());
else OrderPrint();
return(0);
}
}
}
}
}
cnt--;
}
if (!IsTesting())
{
if (myOrderType==3 && OpenOrders<1) { text=text + "\nTIADA KONDISI UTK OPEN ORDER"; }
//else { text= text + "\n "; }
Comment("HARGA TERAKHIR=",LastPrice," OPEN ODER YG LEPAS=",PreviousOpenOrders,"\nBUKA LAGI=",ContinueOpening," JENISORDER=",myOrderType,"\nLOT=",lotsi,text);
}
if (OpenOrders<1)
OpenMarketOrders();
else
if (SetLimitOrders) OpenLimitOrders();
else OpenMarketOrders();
//----
return(0);
}
//+------------------------------------------------------------------+
void OpenMarketOrders()
{
int cnt=0;
if (myOrderType==1 && ContinueOpening)
{
if ((Bid-LastPrice)>=Pips*Point || OpenOrders<1)
{
SellPrice=Bid;
LastPrice=0;
if (TakeProfit==0) { tp=0; }
else { tp=SellPrice-TakeProfit*Point; }
if (StopLoss==0) { sl=0; }
else { sl=SellPrice+StopLoss*Point; }
if (OpenOrders!=0)
{
mylotsi=lotsi;
for(cnt=0;cnt<OpenOrders;cnt++)
{
if (MaxTrades>12) { mylotsi=NormalizeDouble(mylotsi*multiply,2); }
else { mylotsi=NormalizeDouble(mylotsi*multiply,2); }
}
} else { mylotsi=lotsi; }
if (mylotsi>100) { mylotsi=100; }
OrderSend(Symbol(),OP_SELL,mylotsi,SellPrice,slippage,sl,tp,"MyMEFx EA"+MagicNumber,MagicNumber,0,ArrowsColor);
return(0);
}
// Sleep(6000); ////aku letak
// RefreshRates();
}
if (myOrderType==2 && ContinueOpening)
{
if ((LastPrice-Ask)>=Pips*Point || OpenOrders<1)
{
BuyPrice=Ask;
LastPrice=0;
if (TakeProfit==0) { tp=0; }
else { tp=BuyPrice+TakeProfit*Point; }
if (StopLoss==0) { sl=0; }
else { sl=BuyPrice-StopLoss*Point; }
if (OpenOrders!=0) {
mylotsi=lotsi;
for(cnt=0;cnt<OpenOrders;cnt++)
{
if (MaxTrades>12) { mylotsi=NormalizeDouble(mylotsi*multiply,2); }
else { mylotsi=NormalizeDouble(mylotsi*multiply,2); }
}
} else { mylotsi=lotsi; }
if (mylotsi>100) { mylotsi=100; }
OrderSend(Symbol(),OP_BUY,mylotsi,BuyPrice,slippage,sl,tp,"MyMEFx EA"+MagicNumber,MagicNumber,0,ArrowsColor);
return(0);
}
}
}
void OpenLimitOrders()
{
int cnt=0;
if (myOrderType==1 && ContinueOpening)
{
//if ((Bid-LastPrice)>=Pips*Point || OpenOrders<1)
//{
//SellPrice=Bid;
SellPrice = LastPrice+Pips*Point;
LastPrice=0;
if (TakeProfit==0) { tp=0; }
else { tp=SellPrice-TakeProfit*Point; }
if (StopLoss==0) { sl=0; }
else { sl=SellPrice+StopLoss*Point; }
if (OpenOrders!=0)
{
mylotsi=lotsi;
for(cnt=0;cnt<OpenOrders;cnt++)
{
if (MaxTrades>12) { mylotsi=NormalizeDouble(mylotsi*multiply,2); }
else { mylotsi=NormalizeDouble(mylotsi*multiply,2); }
}
} else { mylotsi=lotsi; }
if (mylotsi>100) { mylotsi=100; }
OrderSend(Symbol(),OP_SELLLIMIT,mylotsi,SellPrice,slippage,sl,tp,"MyMEFx EA"+MagicNumber,MagicNumber,0,ArrowsColor);
return(0);
//}
}
if (myOrderType==2 && ContinueOpening)
{
//if ((LastPrice-Ask)>=Pips*Point || OpenOrders<1)
//{
//BuyPrice=Ask;
BuyPrice=LastPrice-Pips*Point;
LastPrice=0;
if (TakeProfit==0) { tp=0; }
else { tp=BuyPrice+TakeProfit*Point; }
if (StopLoss==0) { sl=0; }
else { sl=BuyPrice-StopLoss*Point; }
if (OpenOrders!=0) {
mylotsi=lotsi;
for(cnt=0;cnt<OpenOrders;cnt++)
{
if (MaxTrades>12) { mylotsi=NormalizeDouble(mylotsi*multiply,2); }
else { mylotsi=NormalizeDouble(mylotsi*multiply,2); }
}
} else { mylotsi=lotsi; }
if (mylotsi>100) { mylotsi=100; }
OrderSend(Symbol(),OP_BUYLIMIT,mylotsi,BuyPrice,slippage,sl,tp,"MyMEFx EA"+MagicNumber,MagicNumber,0,ArrowsColor);
return(0);
//}
}
}
void DeleteAllObjects()
{
int obj_total=ObjectsTotal();
string name;
for(int i=0;i<obj_total;i++)
{
name=ObjectName(i);
if (name!="")
ObjectDelete(name);
}
ObjectDelete("FLP_txt");
ObjectDelete("P_txt");
}
// 16
int OpenOrdersBasedOnRSI()
{
int myOrderType=3;
double hma4_1, hma4_2;
double hma6_1, hma6_2;
double hma8_1, hma8_2;
double hma10_1, hma10_2;
double hma20_1, hma20_2;
double hma40_1, hma40_2;
double hma80_1, hma80_2;
double hma200_1, hma200_2;
double hma420_1, hma420_2;
if (last_bar < 0) {
last_bar = 1;
}
hma4_1 = iCustom(Symbol(), 0, "HMA_v07.1", 4, 200, 1, last_bar);
hma4_2 = iCustom(Symbol(), 0, "HMA_v07.1", 4, 200, 1, last_bar + 1);
hma6_1 = iCustom(Symbol(), 0, "HMA_v07.1", 6, 200, 1, last_bar);
hma6_2 = iCustom(Symbol(), 0, "HMA_v07.1", 6, 200, 1, last_bar + 1);
hma8_1 = iCustom(Symbol(), 0, "HMA_v07.1", 8, 200, 1, last_bar);
hma8_2 = iCustom(Symbol(), 0, "HMA_v07.1", 8, 200, 1, last_bar + 1);
hma10_1 = iCustom(Symbol(), 0, "HMA_v07.1", 10, 500, 1, last_bar);
hma10_2 = iCustom(Symbol(), 0, "HMA_v07.1", 10, 500, 1, last_bar + 1);
hma20_1 = iCustom(Symbol(), 0, "HMA_v07.1", 20, 500, 1, last_bar);
hma20_2 = iCustom(Symbol(), 0, "HMA_v07.1", 20, 500, 1, last_bar + 1);
hma40_1 = iCustom(Symbol(), 0, "HMA_v07.1", 40, 800, 1, last_bar);
hma40_2 = iCustom(Symbol(), 0, "HMA_v07.1", 40, 800, 1, last_bar + 1);
hma80_1 = iCustom(Symbol(), 0, "HMA_v07.1", 80, 800, 1, last_bar);
hma80_2 = iCustom(Symbol(), 0, "HMA_v07.1", 80, 800, 1, last_bar + 1);
hma200_1 = iCustom(Symbol(), 0, "HMA_v07.1", 200, 1000, 1, last_bar);
hma200_2 = iCustom(Symbol(), 0, "HMA_v07.1", 200, 1000, 1, last_bar + 1);
hma420_1 = iCustom(Symbol(), 0, "HMA_v07.1", 420, 2000, 1, last_bar);
hma420_2 = iCustom(Symbol(), 0, "HMA_v07.1", 420, 2000, 1, last_bar + 1);
if (
hma420_1 > hma420_2 &&
hma200_1 > hma200_2 &&
hma200_2 > hma420_2 &&
hma4_1 > hma6_1 &&
hma6_1 > hma8_1 &&
hma8_1 > hma10_1 &&
hma10_1 > hma20_1 &&
hma20_1 > hma40_1 &&
hma40_1 > hma80_1 &&
hma4_1 > hma4_2 &&
hma6_1 > hma6_2 &&
hma8_1 > hma8_2 &&
hma10_1 > hma10_2 &&
hma20_1 > hma20_2 &&
hma40_1 > hma40_2 &&
hma80_1 > hma80_2 &&
long
)
{
myOrderType=2;
}
//buy order
if (
hma420_1 < hma420_2 &&
hma200_1 < hma200_2 &&
hma200_2 < hma420_2 &&
hma4_1 < hma6_1 &&
hma6_1 < hma8_1 &&
hma8_1 < hma10_1 &&
hma10_1 < hma20_1 &&
hma20_1 < hma40_1 &&
hma40_1 < hma80_1 &&
hma4_1 < hma4_2 &&
hma6_1 < hma6_2 &&
hma8_1 < hma8_2 &&
hma10_1 < hma10_2 &&
hma20_1 < hma20_2 &&
hma40_1 < hma40_2 &&
hma80_1 < hma80_2 &&
short
)
{
myOrderType=1;
}
return(myOrderType);
}
// Hedge orders manager
void hedgeManager() {
int MagicNumber_hedge_sell = MagicNumber + 1;
int MagicNumber_hedge_buy = MagicNumber + 2;
bool result = false;
double order_sl, sl;
int cnt, hedge_sl;
int Pips_buy = 0;
int Pips_sell = 0;
bool result_close=false;
string buy_ord_numbers, sell_ord_numbers;
double hedge_sell_profit, hedge_buy_profit;
// Close Hedge Orders if price goes our direction
for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
{ //1
Pips_buy = 0;
Pips_sell = 0;
buy_ord_numbers = "";
sell_ord_numbers= "";
result_close = false;
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
//.... Add closing by date here (hedge and all related orders)
if (OrderSymbol()==Symbol() && OrderMagicNumber() == MagicNumber_hedge_sell) //Max_Days_Hedge_Open*24*60*60
{//2
hedge_sl = getPipsForSL(OrderOpenPrice(),OrderStopLoss(),OrderType());
hedge_sell_profit = OrderLots()*(OrderOpenPrice() - Ask);
// Checking if our main trades improved (sum(pips) > )
for(int cnt_s = OrdersTotal()-1; cnt_s>=0; cnt_s--)
{//3
if (OrderSelect(cnt_s, SELECT_BY_POS, MODE_TRADES))
{//4
if (OrderType() == OP_BUY)
{//5
order_sl = getPipsForSL(OrderOpenPrice(),OrderStopLoss(),OrderType());
if (OrderSymbol()==Symbol() && OrderMagicNumber() == MagicNumber && order_sl>0
&& order_sl==hedge_sl)
{//6
if ((Bid - OrderOpenPrice()) < 0)
{//7
if (Pips_buy==0) buy_ord_numbers = ""+ OrderTicket();
else buy_ord_numbers = buy_ord_numbers +","+ OrderTicket();
Pips_buy = Pips_buy + MathAbs(Bid - OrderOpenPrice())/Point;
}//7
hedge_sell_profit = hedge_sell_profit + OrderLots()*(Bid - OrderOpenPrice());
}//6
}//5
}//4
}//3
// end for
if ((StringLen(buy_ord_numbers)>0 && Pips_buy <
(Max_Loss_For_Hedge_pips - Pips_Less_Then_Max_Closing) && Hedge_Lots_Multiplier==1)
|| (Hedge_Lots_Multiplier>1 && hedge_sell_profit > 0))
{//3
if (OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
{//4
Print("Close SELL Hedge Order==>", OrderTicket()," Orders:",buy_ord_numbers);
result_close = OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),slippage,ArrowsColor);
LastHedgeAction = TimeCurrent();
}//4
for(int cnt_bs = OrdersTotal()-1; result_close && cnt_bs>=0; cnt_bs--)
{//4
if (OrderSelect(cnt_bs, SELECT_BY_POS, MODE_TRADES))
{//5
if (OrderType() == OP_BUY)
{//6
order_sl = getPipsForSL(OrderOpenPrice(),OrderStopLoss(),OrderType());
if (OrderSymbol()==Symbol() && OrderMagicNumber() == MagicNumber && order_sl>0
&& order_sl==hedge_sl)
{//7
if (Hedge_Lots_Multiplier>1 && hedge_sell_profit > 0)
{ //8
result = OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),slippage,ArrowsColor);
} //8
else
{ //8
if (StopLoss==0) { sl = 0; }
else { sl = OrderOpenPrice()-StopLoss*Point;}
result=OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0,Purple);
if(! result) Print("Error during Modify BUY Hedge linked order: ", GetLastError());
else Print("Modify correspondent BUY Order==>", OrderTicket());
} //8
}//7
}//6
}//5
}//4
// end for
}//3
}//2
//.... Add closing by date here (hedge and all related orders)
else if (OrderSymbol()==Symbol() && OrderMagicNumber() == MagicNumber_hedge_buy) // Max_Days_Hedge_Open*24*60*60
{//2
hedge_sl = getPipsForSL(OrderOpenPrice(),OrderStopLoss(),OrderType());
hedge_buy_profit = OrderLots()*(Bid - OrderOpenPrice());
// Checking if our main trades improved (sum(pips) > )
for(int cnt_b = OrdersTotal()-1; cnt_b>=0; cnt_b--)
{//3
if (OrderSelect(cnt_b, SELECT_BY_POS, MODE_TRADES))
{//4
if (OrderType() == OP_SELL)
{//5
order_sl = getPipsForSL(OrderOpenPrice(),OrderStopLoss(),OrderType());
if (OrderSymbol()==Symbol() && OrderMagicNumber() == MagicNumber
&& order_sl>0 && order_sl==hedge_sl)
{//6
if ((OrderOpenPrice() - Ask) < 0)
{ //7
if (Pips_sell==0) sell_ord_numbers = ""+ OrderTicket();
else sell_ord_numbers = sell_ord_numbers +","+ OrderTicket();
Pips_sell = Pips_sell + MathAbs(OrderOpenPrice() - Ask)/Point;
}
hedge_buy_profit = hedge_buy_profit + (OrderOpenPrice() - Ask);
}//6
}//5
}//4
}//3
// end for
if ((StringLen(sell_ord_numbers)>0 && Pips_sell <
(Max_Loss_For_Hedge_pips - Pips_Less_Then_Max_Closing) &&
Hedge_Lots_Multiplier==1) || (Hedge_Lots_Multiplier > 1 &&
hedge_sell_profit > 0))
{//3
if (OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
{//4
Print("Close BUY Hedge Order==>", OrderTicket()," Orders:",sell_ord_numbers);
result_close=OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),slippage,ArrowsColor);
LastHedgeAction = TimeCurrent();
}//4
for(int cnt_sb = OrdersTotal()-1; result_close && cnt_sb>=0; cnt_sb--)
{//4
if (OrderSelect(cnt_sb, SELECT_BY_POS, MODE_TRADES))
{//5
if (OrderType() == OP_SELL)
{//6
order_sl = getPipsForSL(OrderOpenPrice(),OrderStopLoss(),OrderType());
if (OrderSymbol()==Symbol() && OrderMagicNumber() == MagicNumber
&& order_sl>0 && order_sl==hedge_sl)
{//7
if (Hedge_Lots_Multiplier>1 && hedge_buy_profit > 0)
{ //8
result = OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),slippage,ArrowsColor);
} //8
else
{ //8
if (StopLoss==0) { sl=0; }
else { sl = OrderOpenPrice()+StopLoss*Point;}
result=OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0,Purple);
if(! result) Print("Error during Modify BUY Hedge linked order: ", GetLastError());
else Print("Modify correspondent SELL Order==>", OrderTicket());
} //8
}//7
} //6
}//5
}//4
// end for
} //3
}//2
// end else
}//1
// end for
// Here Hedge Orders are open....
// - Open only if Last Open/Close was 2 min ago...
int loss_pips = 0;
Pips_buy = 0;
Pips_sell = 0;
int result_open = 0;
double Lots_sell = 0;
double Lots_buy = 0;
buy_ord_numbers = "";
sell_ord_numbers= "";
//Print ("Time diff",TimeCurrent() - LastHedgeAction,Max_Loss_For_Hedge_pips);
if (Max_Loss_For_Hedge_pips > 0) // (TimeCurrent() - LastHedgeAction) > 2*60 &&
{
for(cnt=OrdersTotal()-1; cnt>=0; cnt--)
{
if (OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
{
loss_pips = getPipsForSL(OrderOpenPrice(),OrderStopLoss(), OrderType());
//Print("Ticket",OrderTicket()," Bid:",(Bid - OrderOpenPrice())/Point,"Ask:",(OrderOpenPrice() - Ask));
//if (OrderSymbol()==Symbol() && OrderMagicNumber() == MagicNumber &&
// loss_pips <= Max_SL_pips)
// Print ("Ticket ",OrderTicket()," ",OrderSymbol(),",",Symbol(),",",OrderMagicNumber(),",",MagicNumber,",",loss_pips,",",Max_SL_pips);
//Print (loss_pips,",",Max_SL_pips);
if (OrderSymbol()==Symbol() && OrderMagicNumber() == MagicNumber &&
loss_pips < Max_SL_pips)
{
//Print ("We are here");
if (OrderType()==OP_BUY && (Bid - OrderOpenPrice()) < 0)
{
if (Pips_buy==0) buy_ord_numbers = ""+ OrderTicket();
else buy_ord_numbers = buy_ord_numbers +","+ OrderTicket();
Pips_buy = Pips_buy + MathAbs(Bid - OrderOpenPrice())/Point; // Here should be loss in pips
Lots_sell = Lots_sell + OrderLots();
//Print ("Pips_buy",Pips_buy," Pips_sell",Pips_sell);
}
else if (OrderType()==OP_SELL && (OrderOpenPrice() - Ask) < 0)
{
if (Pips_sell==0) sell_ord_numbers = ""+ OrderTicket();
else sell_ord_numbers = sell_ord_numbers +","+ OrderTicket();
Pips_sell = Pips_sell + MathAbs(OrderOpenPrice() - Ask)/Point; // Here should be loss in pips
Lots_buy = Lots_sell + OrderLots();
}
}
}
}
//if (Pips_buy !=0 || Pips_sell!=0)
//Print ("Pips_buy",Pips_buy," Pips_sell",Pips_sell);
// Create the Hedge
if (Pips_buy >= Max_Loss_For_Hedge_pips) {
//Print("Pips_buy:",Pips_buy," Max_Loss_For_Hedge_pips",Max_Loss_For_Hedge_pips);
// -- Create 1 SELL order, Lots_sell, SL = Next hedge SL, MAGIC#= +1
int sell_hedge_sl = getNextHedgeSL();
Print("Create new SELL hedge Order==>");
result_open = OrderSend(Symbol(),OP_SELL,getLots(Hedge_Lots_Multiplier*Lots_sell), Bid ,
slippage,Bid+sell_hedge_sl*Point,0,"MyMEFx-SL:"+sell_hedge_sl+" for:"+buy_ord_numbers,
MagicNumber_hedge_sell,0,ArrowsColor);
LastHedgeAction = TimeCurrent();
for(int cnt_b_mod =OrdersTotal()-1; result_open>=0 && cnt_b_mod>=0; cnt_b_mod--)
{
if (OrderSelect(cnt_b_mod, SELECT_BY_POS, MODE_TRADES))
{
if (OrderSymbol()==Symbol() && OrderMagicNumber() == MagicNumber &&
OrderType()==OP_BUY && StringFind(buy_ord_numbers,""+OrderTicket(),0)>=0 )
{
result=OrderModify(OrderTicket(),OrderOpenPrice(),
OrderOpenPrice()-sell_hedge_sl*Point,OrderTakeProfit(),0,Purple);
if(result!=TRUE) Print("LastError = ", GetLastError());
else Print("Modify SL for correspondent BUY orders==>");
}
}
}
}
if (Pips_sell >= Max_Loss_For_Hedge_pips) {
// -- Create 1 BUY order, Lots_buy, SL = Next hedge SL, MAGIC#= +2
int buy_hedge_sl = getNextHedgeSL();
Print("Create new BUY hedge Order==>");
result_open=OrderSend(Symbol(),OP_BUY,getLots(Hedge_Lots_Multiplier*Lots_buy), Ask ,slippage,
Ask-buy_hedge_sl*Point,0,
"MyMEFx-SL:"+buy_hedge_sl,MagicNumber_hedge_buy,0,ArrowsColor);
LastHedgeAction = TimeCurrent();
for(int cnt_s_mod =OrdersTotal()-1; result_open>=0 && cnt_s_mod>=0;cnt_s_mod--)
{
if (OrderSelect(cnt_s_mod, SELECT_BY_POS, MODE_TRADES))
{
if (OrderSymbol()==Symbol() && OrderMagicNumber() == MagicNumber &&
OrderType()==OP_SELL && StringFind(sell_ord_numbers,""+OrderTicket(),0)>=0)
{
result=OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+buy_hedge_sl*Point,
OrderTakeProfit(),0,Purple);
if(result!=TRUE) Print("LastError = ", GetLastError());
else Print("Modify SL for correspondent SELL orders==>");
}
}
}
}
}
// end of the method
}
//===============================
int getPipsForSL(double ord_open,double ord_sl, int dir)
{
int val = 0;
if(dir == OP_SELL && ord_sl>0)
val=((ord_sl - ord_open)/Point);
else if (dir == OP_BUY && ord_sl>0)
val=(ord_open - ord_sl)/Point;
return(val);
}
int getNextHedgeSL()
{
bool ord_exists = false;
int ret = 0;
for (ret = Max_SL_pips+200; ret > Max_SL_pips; ret--)
{
for(int cnt_ini = OrdersTotal()-1;cnt_ini >=0;cnt_ini--)
{
if (OrderSelect(cnt_ini, SELECT_BY_POS, MODE_TRADES))
{
ord_exists = false;
if (OrderSymbol()==Symbol() && (OrderMagicNumber() == MagicNumber + 1 || OrderMagicNumber() == MagicNumber + 2) &&
getPipsForSL(OrderOpenPrice(),OrderStopLoss(), OrderType())==ret)
{
//Print(ret+" exists======>");
ord_exists = true;
break;
}
}
}
if (ord_exists)
break;
}
if (ord_exists) ret++;
if (ret>Max_SL_pips+200) ret= Max_SL_pips;
//Print("Final value: "+ret);
return(ret);
}
double getLots(double lot)
{
double ret_lot;
double StepLots=MarketInfo(Symbol(),MODE_LOTSTEP);
ret_lot = NormalizeDouble(lot/StepLots,0)*StepLots;
return (ret_lot);
}
Comments
Markdown Formatting Guide
# H1
## H2
### H3
**bold text**
*italicized text*
[title](https://www.example.com)

`code`
```
code block
```
> blockquote
- Item 1
- Item 2
1. First item
2. Second item
---