X trader v3

Author: Copyright � 2013, www.FxAutomated.com
Profit factor:
0.82

Okay, here's a breakdown of what this MetaTrader script does, explained in simple terms for someone who doesn't code:

This script is designed to automatically trade on the Forex market based on a few specific rules and settings you provide. Imagine it as a robot following instructions to buy or sell currency pairs.

Here's a step-by-step explanation of its logic:

  1. Setup (Input Parameters): The script starts by asking you, the user, to define several key settings. These settings control how the robot behaves:

    • Lots: This is the size of each trade the robot will make (e.g., 0.1 standard lots). Think of it as how much money you're putting into each trade.

    • Slippage: This accounts for small price variations that can happen between when the robot decides to trade and when the trade actually goes through. A buffer to ensure your trade still executes.

    • TakeProfit: This is the profit level at which the robot will automatically close a winning trade. It's the target profit you want to achieve.

    • StopLoss: This is the loss level at which the robot will automatically close a losing trade. It's the maximum loss you're willing to risk.

    • AllowBuy/AllowSell: These are simple on/off switches to let the robot buy, sell, or both.

    • CloseOnReverseSignal: A setting that dictates whether the robot should close an existing trade when a signal occurs that is opposite the current trade direction.

    • TimeSettings/StartTime/EndTime: Defines a specific time window during which the robot is allowed to trade.

    • Ma1/Ma2 Settings: Settings related to moving averages. It uses two sets of moving averages to generate trading signals. Moving averages are calculations of the average price of an asset over a specific period. The script uses the parameters to define the period, shift, method (like simple moving average), and the price that's used in the average calculation.

    • MagicNumber: A unique identifier to help the robot manage its own trades and distinguish them from other trades you might have open.

  2. Initial Checks: Once started, the robot performs several checks:

    • Order Check: The robot scans all open orders in your trading account, focusing on those placed by itself (identified by the "MagicNumber"). It checks if there are existing buy or sell orders for the currency pair it is configured for. It also calculates any profit or loss of current positions.

    • Time Check: It verifies whether the current time falls within the trading window specified by the StartTime and EndTime settings. If it is not within the permitted timeframe, it stops the processes.

  3. Trading Signal Generation: The core of the robot lies in its trading signals.

    • Moving Average Analysis: The script calculates moving averages of prices. It uses two different sets of moving averages (based on the Ma1 and Ma2 settings) to generate buy or sell signals.
    • Buy/Sell Signal Logic:
      • The script compares the current values of these moving averages, using those comparisons to determine whether a buy signal, sell signal, or neither is present.
  4. Order Execution: The script then acts upon those signals:

    • Buy Order: If a buy signal is present, and buying is allowed (based on the AllowBuy setting), and time is within the allowed timeframe, the robot places a buy order for the specified "Lots" size.

    • Sell Order: If a sell signal is present, and selling is allowed (based on the AllowSell setting), and time is within the allowed timeframe, the robot places a sell order.

    • Freeze Feature The script has a "freeze" feature that may affect when new trades are opened. When a buy signal happens, the freeze variable is set to "Buying trend" and when a sell signal happens the freeze variable is set to "Selling trend". The values that freeze takes, prevent the script from opening new trades in the same direction until the freeze variable takes a different value.

  5. Order Management (Closing and Modifying Orders): The robot monitors open trades and adjusts them as needed:

    • Closing on Reverse Signal: If the robot detects a signal that goes against an existing open trade, and the CloseOnReverseSignal setting is enabled, the robot will close that trade.

    • Setting Take Profit and Stop Loss: The robot then sets the TakeProfit and StopLoss levels for the newly opened trade. This automatically closes the trade when the price reaches these levels, limiting losses and securing profits. It checks if TakeProfit and StopLoss are greater than zero, and only modifies orders that doesn't have a TakeProfit or a StopLoss assigned.

  6. Error Handling: The script also includes basic error handling. If certain errors occur during trading (like incorrect stop levels or a busy trading system), the robot will display an alert message and retry the operation, or it will display an alert with the error code.

  7. Deinitialization: Lastly, the robot displays an informative message when removed from the chart, with a website to visit.

In summary, this script is a simple automated trading system that uses moving averages to generate buy and sell signals. It manages trades by setting stop loss and take profit levels, and includes basic error handling. The settings you provide determine how aggressively or conservatively the robot will trade. Remember that automated trading involves risk, and past performance is not indicative of future results.

15 Views
1 Downloads
0 Favorites
X trader v3
//+------------------------------------------------------------------+
//|                                                  X trader v3.mq4 |
//|                            Copyright © 2013, www.FxAutomated.com |
//|                                       http://www.FxAutomated.com |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2013, www.FxAutomated.com"
#property link      "http://www.FxAutomated.com"

//---- input parameters
extern double    Lots=0.1;
extern int       Slip=5;
extern string    StopSettings="Set stops below";
extern double    TakeProfit=150;
extern double    StopLoss=100;
extern bool      AllowBuy=true;
extern bool      AllowSell=true;
extern bool      CloseOnReverseSignal=true;
extern string    TimeSettings="Set the time range the EA should trade";
extern string    StartTime="00:00";
extern string    EndTime="23:59";
extern string    Ma1="First Ma settings";
extern int       Ma1Period=16;
extern int       Ma1Shift=8;
extern int       Ma1Method=MODE_SMA;
extern int       Ma1AppliedPrice=PRICE_MEDIAN;
extern string    Ma2="Second Ma settings";
extern int       Ma2Period=1;
extern int       Ma2Shift=0;
extern int       Ma2Method=MODE_SMA;
extern int       Ma2AppliedPrice=PRICE_MEDIAN;
extern string    MagicNumbers="Set different magicnumber for each timeframe of a pair";
extern int       MagicNumber=103;


string freeze;


int init()
{
return(0);
}
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
//----

int StopMultd=10;
int Slippage=Slip*StopMultd;
double PipsGained,PointsGained;
color CpColor;

int i,closesell=0,closebuy=0;

double  TP=NormalizeDouble(TakeProfit*StopMultd,Digits);
double  SL=NormalizeDouble(StopLoss*StopMultd,Digits);


//-------------------------------------------------------------------+
//Check open orders
//-------------------------------------------------------------------+
if(OrdersTotal()>0){
  for(i=1; i<=OrdersTotal(); i++)          // Cycle searching in orders
     {
      if (OrderSelect(i-1,SELECT_BY_POS)==true) // If the next is available
        {
          if(OrderMagicNumber()==MagicNumber&&OrderSymbol()==Symbol()&&OrderType()==OP_BUY) {int haltbuy=1; }
          if(OrderMagicNumber()==MagicNumber&&OrderSymbol()==Symbol()&&OrderType()==OP_SELL) {int haltsell=1; }
                  
          if((OrderType()==OP_BUY)&&(OrderMagicNumber()==MagicNumber)){
          double difference=Bid-OrderOpenPrice();
          PointsGained=NormalizeDouble(difference/Point,Digits);
          PipsGained=PointsGained/10;
          }
          
          if((OrderType()==OP_SELL)&&(OrderMagicNumber()==MagicNumber)){
          difference=OrderOpenPrice()-Ask;
          PointsGained=NormalizeDouble(difference/Point,Digits);
          PipsGained=PointsGained/10;
          }
          
        }
     }
}

//-------------------------------------------------------------------+
// time check
//-------------------------------------------------------------------
if((TimeCurrent()>=StrToTime(StartTime))&&(TimeCurrent()<=StrToTime(EndTime)))
{
int TradeTimeOk=1;
}
else
{ TradeTimeOk=0; }  
//-----------------------------------------------------------------
// indicator checks
//-----------------------------------------------------------------

// Ma strategy one
double MA1_bc=iMA(NULL,0,Ma1Period,Ma1Shift,Ma1Method,Ma1AppliedPrice,0);
double MA1_bp=iMA(NULL,0,Ma1Period,Ma1Shift,Ma1Method,Ma1AppliedPrice,1);
double MA1_bl=iMA(NULL,0,Ma1Period,Ma1Shift,Ma1Method,Ma1AppliedPrice,2);



// Ma strategy two
double MA2_bc=iMA(NULL,0,Ma2Period,Ma2Shift,Ma2Method,Ma2AppliedPrice,0);
double MA2_bp=iMA(NULL,0,Ma2Period,Ma2Shift,Ma2Method,Ma2AppliedPrice,1);
double MA2_bl=iMA(NULL,0,Ma2Period,Ma2Shift,Ma2Method,Ma2AppliedPrice,2);



  //------------------opening criteria------------------------
if((MA1_bc<MA2_bc)&&(MA1_bp<MA2_bp)&&(MA1_bl>MA2_bl))
{ bool buysignal=true;}else{ buysignal=false; }

if((MA1_bc>MA2_bc)&&(MA1_bp>MA2_bp)&&(MA1_bl<MA2_bl))
{ bool sellsignal=true;}else{ sellsignal=false; }


//------------------------------closing criteria--------------
if((MA1_bc>MA2_bc)&&(MA1_bp>MA2_bp)&&(MA1_bl<MA2_bl)){closebuy=1; }else{ closebuy=0; }
if((MA1_bc<MA2_bc)&&(MA1_bp<MA2_bp)&&(MA1_bl>MA2_bl)){closesell=1; }else{ closesell=0; }




//-----------------------------------------------------------------------------------------------------
// Opening criteria
//-----------------------------------------------------------------------------------------------------


// Open buy
 if((buysignal==true)&&(closebuy!=1)&&(freeze!="Buying trend")&&(TradeTimeOk==1)){
 
   if(AllowBuy==true&&haltbuy!=1)int openbuy=OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,0,0,"Stochastic rsi buy order",MagicNumber,0,Blue);
 
 }


// Open sell
 if((sellsignal==true)&&(closesell!=1)&&(freeze!="Selling trend")&&(TradeTimeOk==1)){

 if(AllowSell==true&&haltsell!=1) int opensell=OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,0,0,"Stochastic rsi sell order",MagicNumber,0,Red);

 }
 


if(buysignal==true){freeze="Buying trend";}
if(sellsignal==true){freeze="Selling trend";}


//-------------------------------------------------------------------------------------------------
// Closing criteria
//-------------------------------------------------------------------------------------------------

if(closesell==1||closebuy==1||openbuy<1||opensell<1){// start
if(OrdersTotal()>0){
  for(i=1; i<=OrdersTotal(); i++){          // Cycle searching in orders
  
      if (OrderSelect(i-1,SELECT_BY_POS)==true){ // If the next is available
          if(CloseOnReverseSignal==true){
          if(OrderMagicNumber()==MagicNumber&&closebuy==1&&OrderType()==OP_BUY&&OrderSymbol()==Symbol()) { OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,CLR_NONE); }
          if(OrderMagicNumber()==MagicNumber&&closesell==1&&OrderType()==OP_SELL&&OrderSymbol()==Symbol()) { OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,CLR_NONE); }
          }
          // set stops
          
                // Calculate take profit
                double tpb=NormalizeDouble(OrderOpenPrice()+TP*Point,Digits);
                double tps=NormalizeDouble(OrderOpenPrice()-TP*Point,Digits);
                // Calculate stop loss
                double slb=NormalizeDouble(OrderOpenPrice()-SL*Point,Digits);
                double sls=NormalizeDouble(OrderOpenPrice()+SL*Point,Digits);

          
          if(TakeProfit>0){// if tp not 0
          if((OrderMagicNumber()==MagicNumber)&&(OrderTakeProfit()==0)&&(OrderSymbol()==Symbol())&&(OrderType()==OP_BUY)){ OrderModify(OrderTicket(),0,OrderStopLoss(),tpb,0,CLR_NONE); }
          if((OrderMagicNumber()==MagicNumber)&&(OrderTakeProfit()==0)&&(OrderSymbol()==Symbol())&&(OrderType()==OP_SELL)){ OrderModify(OrderTicket(),0,OrderStopLoss(),tps,0,CLR_NONE); }
          }
          
          if(StopLoss>0){// if sl not 0
          if((OrderMagicNumber()==MagicNumber)&&(OrderStopLoss()==0)&&(OrderSymbol()==Symbol())&&(OrderType()==OP_BUY)){ OrderModify(OrderTicket(),0,slb,OrderTakeProfit(),0,CLR_NONE);  }
          if((OrderMagicNumber()==MagicNumber)&&(OrderStopLoss()==0)&&(OrderSymbol()==Symbol())&&(OrderType()==OP_SELL)){ OrderModify(OrderTicket(),0,sls,OrderTakeProfit(),0,CLR_NONE);  }
          }
          

          
        } // if available
     } // cycle
}// orders total


}// stop



//----
int Error=GetLastError();
  if(Error==130){Alert("Wrong stops. Retrying."); RefreshRates();}
  if(Error==133){Alert("Trading prohibited.");}
  if(Error==2){Alert("Common error.");}
  if(Error==146){Alert("Trading subsystem is busy. Retrying."); Sleep(500); RefreshRates();}

//----

//-------------------------------------------------------------------
   return(0);
  }
//+--------------------------------End----------------------------------+








































































































int deinit()
{
  Alert("Visit www.fxautomated.com for more forex tools");
  return;
}

Comments