Orders Execution
Indicators Used
0
Views
0
Downloads
0
Favorites
Samuray_v7
//+------------------------------------------------------------------+
//| Samuray.mq4 |
//| Kokas |
//| http://www.forexforums.org |
//| Check EA Main thread at: |
//| http://www.forexforums.org/showthread.php?t=1888 |
//+------------------------------------------------------------------+
#property copyright "Kokas"
#property link "http://www.forexforums.org"
//---- input parameters
extern string ExpertName = "Samuray V.7";
extern bool AutoTrade = true;
extern double RecycleProfit = 2900;
extern int MaxTrades = 20; // Set to 0 to use Automatic calculation of Maxtrades
extern bool AutoMaxTrades = true;
extern int PreventPos = 10; // Prevent the opening of a new position if there are other near
extern bool UseLongs = true;
extern bool UseShorts = false;
extern bool UseSwap = false;
extern double InitialStop = 1000; // Initial StopLoss Set for every Order
extern double BreakEven = 100; // Profit Lock in pips
extern double BEOffset = 10; // BreakEven profit capture
extern double TrailStop = 250; //
extern bool SecureOrders = true; // If set to true only open orders when in profit MinPip
extern double MinPips = 20; // Min Profit Pips to open another order (read above)
extern bool CloseAll = false; // Set true to close all current Orders
extern int Magic = 5665; // Magic Number of the EA
extern double Lots = 0.01; // Lot size when not using MM
extern bool MoneyManagement = true; // Set to true to use Money Management
extern double MaxLotSize = 1.5; // Max Lot size when using Money Management
extern double Risk = 15; // Risk factor when using MM
extern string RSI = "RSI FILTER SETTINGS"; //
extern bool UseRSI = true;
extern int RSIPeriod = 7;
extern int RSITimeFrame = 0;
extern int UpperRSI = 75;
extern int LowerRSI = 25;
extern string EMA = "EMA FILTER SETTINGS";
extern int ShortEma = 15;
extern int LongEma = 110; // Minimum diference between EMA's that allow opening
extern int MinEmaDiverg = 10;
extern bool CloseOnEmaCross = true; // Close all orders if EMA's reverse
extern string GLOBALMANAGEMENT = "Global Settings";
extern int TotalStopLoss = 0; // Close all Trades if reached
extern int GlobalBE = 1000; // Lock all positions when reached
extern int GlobalBEOffset = 800; // Global BreakEven Offset
//extern int GlobalTrailStop = 2000;
extern bool UseReport = false; // Print Entried on Journal
int k, digit=0;
double AccountSize,totalPips,totalProfits,SEma,LEma,error,shortPips,longPips,sidePips, MaxT;
double pBid, pAsk, pp,valueswap,RSIValue;
bool AccountIsMicro;
bool signal1 = true, signal2 =true, signal3 = true , signal4 = true, signal5 = true, signal6 = true, SecureSignal = true, RSISignal = true;
string comment = "";
//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init()
{
//----
if (MarketInfo(Symbol(),MODE_LOTSTEP) == 0.01)
{
AccountIsMicro = true;
}
else
{
AccountIsMicro = false;
}
//----
return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----
//----
return(0);
}
void ChartComment()
{
string sComment = "";
string sp = "****************************\n";
string NL = "\n";
sComment = sp;
sComment = sComment + "** SAMURAY\n" + sp;
sComment = sComment + "Open Positions = " + ScanOpenTrades() + " / " + MaxTrades + NL;
sComment = sComment + "Locked Positions = " + CheckLocked() + NL;
sComment = sComment + "Current Profit(Pip) = " + DoubleToStr(totalPips,0) + NL;
if(UseSwap) sComment = sComment + "SWAP Value (Pip) = " + DoubleToStr(valueswap,2) + NL;
sComment = NL + sComment + "Net Value (Pip) = " + DoubleToStr(totalPips+valueswap,0) + NL;
sComment = NL + sComment + "Account Leverage: " + DoubleToStr(AccountLeverage(),0) + NL;
sComment = sComment + NL + sp;
Comment(sComment);
}
int ScanOpenTrades()
{
int total = OrdersTotal();
int numords = 0;
for(int cnt=0; cnt<=total-1; cnt++)
{
OrderSelect(cnt, SELECT_BY_POS);
if(OrderType()<=OP_SELL)
{
if(Magic > 0) if(OrderMagicNumber() == Magic) numords++;
if(Magic == 0) numords++;
}
}
return(numords);
}
// Closing of Open Orders
void OpenOrdClose()
{
int total=OrdersTotal();
for (int cnt=0;cnt<total;cnt++)
{
OrderSelect(total-cnt-1, SELECT_BY_POS);
int mode=OrderType();
bool res = false;
bool condition = false;
if (OrderMagicNumber()==Magic ) condition = true;
if (condition && ( mode==OP_BUY || mode==OP_SELL ))
{
// - BUY Orders
if(mode==OP_BUY)
{
res = OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_BID),3,Yellow);
if( !res )
{
Print(" BUY: OrderClose failed with error #",GetLastError());
Print(" Ticket=",OrderTicket());
Sleep(3000);
}
}
else
// - SELL Orders
if( mode == OP_SELL)
{
res = OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_ASK),3,White);
if( !res )
{
Print(" SELL: OrderClose failed with error #",GetLastError());
Print(" Ticket=",OrderTicket());
Sleep(3000);
}
}
}
}
}
void TotalProfit()
{
int total=OrdersTotal();
totalPips = 0;
totalProfits = 0;
for (int cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS);
int mode=OrderType();
bool condition = false;
if ( Magic>0 && OrderMagicNumber()==Magic ) condition = true;
else if ( Magic==0 ) condition = true;
if (condition)
{
switch (mode)
{
case OP_BUY:
totalPips += MathRound((MarketInfo(OrderSymbol(),MODE_BID)-OrderOpenPrice())/MarketInfo(OrderSymbol(),MODE_POINT));
//totalPips += MathRound((Bid-OrderOpenPrice())/Point);
totalProfits += OrderProfit();
break;
case OP_SELL:
totalPips += MathRound((OrderOpenPrice()-MarketInfo(OrderSymbol(),MODE_ASK))/MarketInfo(OrderSymbol(),MODE_POINT));
//totalPips += MathRound((OrderOpenPrice()-Ask)/Point);
totalProfits += OrderProfit();
break;
}
}
if (UseSwap) {
SwapProfit();
totalProfits = totalProfits + valueswap;
}
}
}
void sidePips()
{
int total=OrdersTotal();
shortPips = 0;
longPips = 0;
for (int cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS);
int mode=OrderType();
bool condition = false;
if ( Magic>0 && OrderMagicNumber()==Magic ) condition = true;
else if ( Magic==0 ) condition = true;
if (condition)
{
switch (mode)
{
case OP_BUY:
longPips += MathRound((MarketInfo(OrderSymbol(),MODE_BID)-OrderOpenPrice())/MarketInfo(OrderSymbol(),MODE_POINT));
break;
case OP_SELL:
shortPips += MathRound((OrderOpenPrice()-MarketInfo(OrderSymbol(),MODE_ASK))/MarketInfo(OrderSymbol(),MODE_POINT));
break;
}
}
}
}
// MoneyManagement
double LotSize()
{
double lotMM = MathCeil(AccountFreeMargin() * Risk / 1000) / 1000;
if(AccountIsMicro) {
if(lotMM < 0.01) lotMM = 0.01;
if(lotMM >= MaxLotSize) lotMM = MaxLotSize;
AccountSize=2;
} else {
if(lotMM < 0.1) lotMM = 0.1;
if(lotMM >= MaxLotSize) lotMM = MaxLotSize;
AccountSize=1;
}
lotMM = NormalizeDouble(lotMM,AccountSize);
return (lotMM);
}
void SwapProfit()
{
int total=OrdersTotal();
valueswap = 0;
for (int cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS);
int mode=OrderType();
bool condition = false;
if ( Magic>0 && OrderMagicNumber()==Magic ) condition = true;
else if ( Magic==0 ) condition = true;
if (condition && OrderSwap()!=0)
{
valueswap = valueswap + OrderSwap()/PipCost(OrderSymbol()); // ERROOOOOOOOOOOOOOOOOOOOOOOOOOO
}
}
}
/* bool CheckAllProfit()
{
bool sig = true;
int total=OrdersTotal();
for (int cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS);
int mode=OrderType();
bool condition = false;
if ( Magic>0 && OrderMagicNumber()==Magic ) condition = true;
else if ( Magic==0 ) condition = true;
if (condition)
{
if (MarketInfo(OrderSymbol(),MODE_BID) < OrderOpenPrice())
{
sig = false;
Print(MarketInfo(OrderSymbol(),MODE_BID)," < ", OrderOpenPrice()," NOT ALL ORDERS IN PROFIT !!! ");
}
}
}
if (ScanOpenTrades() == 0) sig = true;
return(sig);
}
*/
bool CheckLocked()
{
int sig = 0;
int total=OrdersTotal();
for (int cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS);
int mode=OrderType();
bool condition = false;
if ( Magic>0 && OrderMagicNumber()==Magic ) condition = true;
else if ( Magic==0 ) condition = true;
if (condition)
{
if (OrderStopLoss() > OrderOpenPrice())
{
sig = sig + 1;
}
}
}
return(sig);
}
//+--------- --------- --------- --------- --------- --------- ----+
//+ Calculate cost in USD of 1pip of given symbol
//+--------- --------- --------- --------- --------- --------- ----+
double PipCost (string TradeSymbol) {
double Base, Cost;
string TS_13, TS_46, TS_4L;
TS_13 = StringSubstr (TradeSymbol, 0, 3);
TS_46 = StringSubstr (TradeSymbol, 3, 3);
TS_4L = StringSubstr (TradeSymbol, 3, StringLen(TradeSymbol)-3);
Base = MarketInfo (TradeSymbol, MODE_LOTSIZE) * MarketInfo (TradeSymbol,MODE_POINT);
if ( TS_46 == "USD" )
Cost = Base;
else if ( TS_13 == "USD" )
Cost = Base / MarketInfo (TradeSymbol, MODE_BID);
else if ( PairExists ("USD"+TS_4L) )
Cost = Base / MarketInfo ("USD"+TS_4L, MODE_BID);
else
Cost = Base * MarketInfo (TS_46+"USD" , MODE_BID);
return(Cost) ;
}
//+--------- --------- --------- --------- --------- --------- ----+
//+ Returns true if given symbol exists
//+--------- --------- --------- --------- --------- --------- ----+
bool PairExists (string TradeSymbol) {
return ( MarketInfo (TradeSymbol, MODE_LOTSIZE) > 0 );
}
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
digit = MarketInfo(Symbol(),MODE_DIGITS);
SEma = iMA(Symbol(),0,ShortEma,0,MODE_EMA,PRICE_CLOSE,0);
LEma = iMA(Symbol(),0,LongEma,0,MODE_EMA,PRICE_CLOSE,0);
if (AutoMaxTrades) MaxTrades = MathCeil(AccountFreeMargin()/(Risk * AccountLeverage()));
MaxTrades = MaxTrades + CheckLocked();
signal1 = false;
signal2 = false;
signal4 = true;
if (CloseAll) {
OpenOrdClose();
signal4 = false;
}
TotalProfit();
sidePips();
if (-TotalStopLoss > totalPips && TotalStopLoss !=0 ) {
OpenOrdClose();
signal4 = false;
}
if (ScanOpenTrades() < MaxTrades) signal1 = true;
signal3 = false;
if (!IsPosition(PreventPos)) signal3 = true;
if (MoneyManagement) Lots = LotSize();
if ((SEma > LEma) && (SEma != LEma)){
signal5 = true;
} else {
signal5 = false;
}
if (signal5)
{
sidePips = longPips;
} else {
sidePips = shortPips;
}
// *************************************************************************************
// RSI FILTER SECTION
// *************************************************************************************
if (UseRSI)
{
RSIValue = iRSI(Symbol(),RSITimeFrame,RSIPeriod,0,0);
RSISignal = false;
if (UseLongs && RSIValue < UpperRSI) RSISignal = true;
if (UseShorts && RSIValue > LowerRSI) RSISignal = true;
} else {
RSISignal = true;
}
// *************************************************************************************
if (SecureOrders){
if (sidePips > MinPips || sidePips == 0){
SecureSignal = true;
} else {
SecureSignal = false;
}
} else {
SecureSignal = true;
}
if (MinEmaDiverg >0)
{
if (MathAbs((SEma-LEma) * 100) > MinEmaDiverg) signal2 = true;
}
if (CloseOnEmaCross) {
if (MathAbs(SEma - LEma)*100 < 1 ) {
OpenOrdClose();
signal4 = false;
}
}
if (sidePips > RecycleProfit) {
if (signal5)
{
OpenLongClose();
} else {
OpenShortClose();
}
signal4 = false;
}
//+------------------------------------------------------------------+
if (UseReport){
if (!signal1) Print("Max trades Reached"); // signal1 - Control the number of open orders
if (!signal2) Print("Divergence on EMAs"); // signal2 - Check the Divergence on EMA's
if (!signal3) Print("Another Position on Proximity"); // signal3 - Bollinger Bands Filter
if (!signal4) Print("Recycling Orders"); // signal4 - Control Recycle Profits
if (!signal5) Print("Ask EMA to enter trades!"); // signal5 - Check EMA's before place trades
if (!AutoTrade) Print("Autotrade disabled on properties");
if (!SecureSignal) Print("Not safe to enter yet");
}
if (signal1 && signal2 && signal3 && signal4 && AutoTrade && SecureSignal && RSISignal){
if (signal5 && UseLongs) {
error = 1;
while (error != 0) {
if (InitialStop > 0){
OrderSend(Symbol(),OP_BUY,Lots,MarketInfo(Symbol(),MODE_ASK),3,Ask-InitialStop*Point,0,ExpertName,Magic,0,Blue);
error = GetLastError();
} else {
OrderSend(Symbol(),OP_BUY,Lots,MarketInfo(Symbol(),MODE_ASK),3,0,0,ExpertName,Magic,0,Blue);
error = GetLastError();
}
if (error !=0 ) Print("Error: ",error);
}
}
if (!signal5 && UseShorts){
error = 1;
while (error != 0) {
if (InitialStop > 0){
OrderSend(Symbol(),OP_SELL,Lots,MarketInfo(Symbol(),MODE_BID),3,Bid+InitialStop*Point,0,ExpertName,Magic,0,Red);
} else {
OrderSend(Symbol(),OP_SELL,Lots,MarketInfo(Symbol(),MODE_BID),3,0,0,ExpertName,Magic,0,Red);
}
error = GetLastError();
if (error !=0 ) Print(error); }
}
}
ChartComment();
if (TrailStop > 0)
{
TrailIt(TrailStop);
}
if (BreakEven > 0)
{
DoBE(BreakEven);
}
if (GlobalBE > 0 && ScanOpenTrades()!=0 )
{
GlobalDoBE(MathCeil(GlobalBE / ScanOpenTrades()));
}
/*
if (GlobalTrailStop > 0 && ScanOpenTrades()!=0)
{
GlobalTrail(MathCeil(GlobalTrailStop / ScanOpenTrades()));
}
*/
return(0);
}
//+------------------------------------------------------------------+
void TrailIt( int byPips ) // based on trailing stop code from MT site... thanks MT!
{
if (byPips >=5)
{
for (int i = 0; i < OrdersTotal(); i++) {
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
if ( OrderSymbol()==Symbol() && ( (OrderMagicNumber() == Magic)) )
{
if (OrderType() == OP_BUY) {
if (Bid - OrderOpenPrice() > byPips * MarketInfo(OrderSymbol(), MODE_POINT)) {
if (OrderStopLoss() < Bid - byPips * MarketInfo(OrderSymbol(), MODE_POINT)) {
OrderModify(OrderTicket(), OrderOpenPrice(), Bid - byPips * MarketInfo(OrderSymbol(), MODE_POINT), OrderTakeProfit(), Red);
}
}
} else if (OrderType() == OP_SELL) {
if (OrderOpenPrice() - Ask > byPips * MarketInfo(OrderSymbol(), MODE_POINT)) {
if ((OrderStopLoss() > Ask + byPips * MarketInfo(OrderSymbol(), MODE_POINT)) ||
(OrderStopLoss() == 0)) {
OrderModify(OrderTicket(), OrderOpenPrice(),
Ask + byPips * MarketInfo(OrderSymbol(), MODE_POINT), OrderTakeProfit(), Red);
}
}
}
}
}
}
} // proc TrailIt()
void DoBE(int byPips)
{
for (int i = 0; i < OrdersTotal(); i++) {
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
if ( OrderSymbol()==Symbol() && ( (OrderMagicNumber() == Magic) ) )
{
if (OrderType() == OP_BUY && (OrderStopLoss() < (OrderOpenPrice() + MarketInfo(OrderSymbol(), MODE_POINT)*BEOffset))) if ((Bid - OrderOpenPrice() > byPips * MarketInfo(OrderSymbol(), MODE_POINT)) && (OrderOpenPrice()-OrderStopLoss() > 0)) if (OrderStopLoss() != (OrderOpenPrice() + MarketInfo(OrderSymbol(), MODE_POINT))) OrderModify(OrderTicket(), OrderOpenPrice(), OrderOpenPrice() + MarketInfo(OrderSymbol(), MODE_POINT)*BEOffset, OrderTakeProfit(), Red);
if (OrderType() == OP_SELL && (OrderStopLoss() > (OrderOpenPrice() + MarketInfo(OrderSymbol(), MODE_POINT)*BEOffset))) if ((OrderOpenPrice() - Ask > byPips * MarketInfo(OrderSymbol(), MODE_POINT)) && (OrderOpenPrice()-OrderStopLoss() > 0)) if (OrderStopLoss() != (OrderOpenPrice() - MarketInfo(OrderSymbol(), MODE_POINT))) OrderModify(OrderTicket(), OrderOpenPrice(), OrderOpenPrice() - MarketInfo(OrderSymbol(), MODE_POINT)*BEOffset, OrderTakeProfit(), Red);
}
}
}
void GlobalDoBE(int byPips)
{
for (int i = 0; i < OrdersTotal(); i++) {
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
if ( OrderSymbol()==Symbol() && ( (OrderMagicNumber() == Magic) ) )
{
if (OrderType() == OP_BUY && (OrderStopLoss() < (OrderOpenPrice() + MarketInfo(OrderSymbol(), MODE_POINT)*BEOffset))) if (OrderStopLoss() != (OrderOpenPrice() + MarketInfo(OrderSymbol(), MODE_POINT))) OrderModify(OrderTicket(), OrderOpenPrice(), OrderOpenPrice() + MarketInfo(OrderSymbol(), MODE_POINT)*byPips, OrderTakeProfit(), Blue);
if (OrderType() == OP_SELL && (OrderStopLoss() > (OrderOpenPrice() + MarketInfo(OrderSymbol(), MODE_POINT)*BEOffset))) if (OrderStopLoss() != (OrderOpenPrice() - MarketInfo(OrderSymbol(), MODE_POINT))) OrderModify(OrderTicket(), OrderOpenPrice(), OrderOpenPrice() - MarketInfo(OrderSymbol(), MODE_POINT)*byPips, OrderTakeProfit(), Blue);
}
}
}
/* void GlobalTrail( int byPips )
{
if (byPips >=5)
{
for (int i = 0; i < OrdersTotal(); i++) {
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
if ( OrderSymbol()==Symbol() && ( (OrderMagicNumber() == Magic)) )
{
if (OrderType() == OP_BUY) {
if (Bid - OrderOpenPrice() > byPips * MarketInfo(OrderSymbol(), MODE_POINT)) {
if (OrderStopLoss() < Bid - byPips * MarketInfo(OrderSymbol(), MODE_POINT)) {
OrderModify(OrderTicket(), OrderOpenPrice(), Bid - byPips * MarketInfo(OrderSymbol(), MODE_POINT), OrderTakeProfit(), Red);
}
}
} else if (OrderType() == OP_SELL) {
if (OrderOpenPrice() - Ask > byPips * MarketInfo(OrderSymbol(), MODE_POINT)) {
if ((OrderStopLoss() > Ask + byPips * MarketInfo(OrderSymbol(), MODE_POINT)) ||
(OrderStopLoss() == 0)) {
OrderModify(OrderTicket(), OrderOpenPrice(),
Ask + byPips * MarketInfo(OrderSymbol(), MODE_POINT), OrderTakeProfit(), Red);
}
}
}
}
}
}
} // proc TrailIt()
*/
bool IsPosition(double inRange)
{
int totalorders = OrdersTotal();
for(int i = 0;i < totalorders;i++)
{
OrderSelect(i, SELECT_BY_POS);
if ((OrderSymbol() == Symbol()) && (OrderMagicNumber() == Magic))
{
int type = OrderType();
if ((MathAbs(OrderOpenPrice() - MarketInfo(Symbol(),MODE_ASK))*90) < (inRange))
{
if (type == OP_BUY || type == OP_SELL)
{
return(true);
}
}
}
}
return(false);
}
void OpenLongClose()
{
int total=OrdersTotal();
for (int cnt=0;cnt<total;cnt++)
{
OrderSelect(total-cnt-1, SELECT_BY_POS);
int mode=OrderType();
bool res = false;
bool condition = false;
if (OrderMagicNumber()==Magic ) condition = true;
if (condition && mode==OP_BUY )
{
res = OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_BID),3,Yellow);
if( !res )
{
Print(" BUY: OrderClose failed with error #",GetLastError());
Print(" Ticket=",OrderTicket());
Sleep(3000);
}
}
}
}
void OpenShortClose()
{
int total=OrdersTotal();
for (int cnt=0;cnt<total;cnt++)
{
OrderSelect(total-cnt-1, SELECT_BY_POS);
int mode=OrderType();
bool res = false;
bool condition = false;
if (OrderMagicNumber()==Magic ) condition = true;
if (condition && mode==OP_SELL )
{
res = OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_ASK),3,White);
if( !res )
{
Print(" SELL: OrderClose failed with error #",GetLastError());
Print(" Ticket=",OrderTicket());
Sleep(3000);
}
}
}
}
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
---