X Trader v2 Logic Overview
This document provides a non-technical explanation of the automated trading logic contained within the X trader v2 script. This system is designed to automatically monitor market trends and execute trades based on specific moving average crossovers.
1. Core Trading Philosophy
The script utilizes two different Moving Averages (MA) to determine the direction of the market. Moving averages are tools that smooth out price data to help identify whether a trend is moving upward (bullish) or downward (bearish). The system looks for specific "crossover" patterns between these two lines to trigger buy and sell actions.
2. Key Components & Parameters
- Moving Average 1 (Fast/Slow Indicator): A primary calculation used to establish the main trend direction.
- Moving Average 2 (Secondary Indicator): A secondary calculation used as a baseline to compare against the first average.
- Trade Volume (Lots): Determines the size of each position opened.
- Take Profit & Stop Loss: These are the "safety nets." The script automatically calculates these levels based on user inputs to lock in profits or limit losses.
3. How the Strategy Works
The script constantly scans the price charts and performs the following logic:
A. Identifying Trends (The Signal)
Instead of looking at just one point in time, the script compares the current state of the moving averages against their positions on previous bars (the immediate past).
- Sell Signal: Triggered when the two moving averages cross in a specific sequence that indicates a downward shift in momentum.
- Buy Signal: Triggered when the two moving averages cross in a sequence that indicates an upward shift in momentum.
B. Trade Execution Rules
To prevent the script from opening multiple unnecessary trades at once, it follows these rules:
- Active Order Check: It checks if there is already an active trade open with its specific identification number ("Magic Number"). If a trade is already running, it will "halt" and wait for that trade to close before looking for new signals.
- Trend Memory: The script tracks the current trend (Buy or Sell) to ensure it doesn't repeatedly enter the same type of trade in a row without a clear change in market conditions.
C. Automatic Trade Management
Once a trade is successfully opened, the script performs "housekeeping" automatically:
- Profit/Loss Protection: The script immediately calculates and attaches the correct Take Profit and Stop Loss levels to the trade based on your settings.
- Dynamic Adjustment: It ensures these levels are correctly formatted for the specific currency pair being traded (Normalizing the price digits).
4. Error Handling & Safety
The script includes a built-in monitoring system to handle common connectivity or market issues:
- Stops Correction: If the broker rejects a trade because the Stop Loss is too close to the current price, the script will alert you and try again.
- Connection Issues: It detects if the trading subsystem is busy or if trading is prohibited by the broker and provides specific alerts to notify the user of these conditions.
Summary of Workflow
- Scan: Monitor Moving Average 1 and Moving Average 2 constantly.
- Analyze: Check if the averages have crossed in a "Buy" or "Sell" pattern.
- Verify: Ensure no other trades are currently open for this specific system.
- Execute: Open the trade at the best current price.
- Protect: Immediately apply Take Profit and Stop Loss levels to the new trade.
- Monitor: Repeat the process until the trade is closed or a new signal appears.
//+------------------------------------------------------------------+
//| X trader v2.mq4 |
//| Copyright © 2013, www.FxAutomated.com |
//| http://www.FxAutomated.com |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2012, www.FxAutomated.com"
#property link "http://www.FxAutomated.com"
//---- input parameters
extern double Lots=0.1;
extern int TakeProfit=150;
extern int StopLoss=100;
extern string Ma1="First Ma settings";
extern int Ma1Period=16;
extern int Ma1Shift=8;
extern int Ma1Method=0;
extern int Ma1AppliedPrice=4;
extern string Ma2="Second Ma settings";
extern int Ma2Period=1;
extern int Ma2Shift=0;
extern int Ma2Method=0;
extern int Ma2AppliedPrice=4;
extern int MagicNumber=320101;
string Trend;
//+------------------------------------------------------------------+
//| expert starts |
//+------------------------------------------------------------------+
int start()
{
//----
int StopMultd,Slip=5;
StopMultd=10;
double TP=NormalizeDouble(TakeProfit*StopMultd,Digits);
// stop loss
double SL=NormalizeDouble(StopLoss*StopMultd,Digits);
double Slippage=NormalizeDouble(Slip*StopMultd,Digits);
// 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 constant
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);
//-------------------------------------------------------------------+
//Check open orders
//-------------------------------------------------------------------+
if(OrdersTotal()>0){
for(int 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()) {int halt1=1;}
}
}
}
//-------------------------------------------------------------------+
//-------------------------------------------------------------------+
// trading strategy
//-------------------------------------------------------------------+
if(halt1!=1){// halt1
// Sell criteria
if ((MA1_bc>MA2_bc)&&(MA1_bp>MA2_bp)&&(MA1_bl<MA2_bl)&&Trend!="SELL") //Signal Sell
{
int opensell=OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,0,0,"X trader 2 trade ",MagicNumber,0,Green);
if(opensell<1){int sellfail=1;}
Trend="SELL";
}
// Buy criteria
if ((MA1_bc<MA2_bc)&&(MA1_bp<MA2_bp)&&(MA1_bl>MA2_bl)&&Trend!="BUY") //Signal Buy
{
int openbuy=OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,0,0,"X trader 2 trade ",MagicNumber,0,Blue);
if(openbuy<1){int buyfail=1;}
Trend="BUY";
}
}// halt1
//-----------------------------------------------------------------------------------------------------
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
// 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((OrderMagicNumber()==MagicNumber&&OrderType()==OP_BUY)&&(OrderTakeProfit()==0||OrderStopLoss()==0)&&OrderSymbol()==Symbol()) { OrderModify(OrderTicket(),0,slb,tpb,0,CLR_NONE); }
if((OrderMagicNumber()==MagicNumber&&OrderType()==OP_SELL)&&(OrderTakeProfit()==0||OrderStopLoss()==0)&&OrderSymbol()==Symbol()) { OrderModify(OrderTicket(),0,sls,tps,0,CLR_NONE); }
}
}
}
//-------------------------------------------------------------------+
// Error processing
//-------------------------------------------------------------------+
if(buyfail==1||sellfail==1){
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 init()
{
Alert("Visit www.FxAutomated.com for more goodies!");
return(0);
}
Comments