//-----
#include
#include
CTrade trade;
CPositionInfo m_position; // object of CPositionInfo class
COrderInfo m_order; // object of COrderInfo class
double Ask,Bid,high,low;
input int contracts = 1;
input double profit = 1000;
input double dailytarget = 2000;
input bool trailingstophighlow = false;
input bool trailingpsar = false;
input bool trailingstopma = false;
input ulong magicnumber = 7000; // magicnumber
input int periods = 20;
//---------
int OnInit()
{
//---
trade.SetExpertMagicNumber(magicnumber); // used to set trades magicnumber sent by other functions
//-------
//---
return(INIT_SUCCEEDED);
}
//------ on tick code
void OnTick()
{
//---
Ask = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);
Bid = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);
high = NormalizeDouble(iHigh(NULL,PERIOD_M15,1),_Digits);
low = NormalizeDouble(iLow(NULL,PERIOD_M15,1),_Digits);
double mas[];
int ma = iMA(NULL,PERIOD_CURRENT,periods,0,MODE_SMA,PRICE_CLOSE);
ArraySetAsSeries(mas,true);
CopyBuffer(ma,0,0,3,mas);
//------
if(trailingstopma && (mas[0] > 0.0))
{
trailingstopma(mas[0]);
}
//----
//----
}
//------- just the function itself
void trailingstopma(double ma) //
{
double newstoploss = NormalizeDouble(ma,_Digits);
for(int i=PositionsTotal()-1; i>=0; i--)
{
string symbol = PositionGetSymbol(i);
ulong pm = PositionGetInteger(POSITION_MAGIC);
if((_Symbol == symbol) && (pm == magicnumber))
{
if(PositionGetInteger(POSITION_TYPE) == ORDER_TYPE_BUY)
{
ulong ticket = PositionGetInteger(POSITION_TICKET);
double currentstoploss = PositionGetDouble(POSITION_SL);
if(currentstoploss < ma)
{
trade.PositionModify(ticket,newstoploss,0);
}
}
if(PositionGetInteger(POSITION_TYPE) == ORDER_TYPE_SELL)
{
ulong ticket = PositionGetInteger(POSITION_TICKET);
double currentstoploss = PositionGetDouble(POSITION_SL);
if(currentstoploss > ma)
{
trade.PositionModify(ticket,newstoploss,0);
}
}
}
}
}