Okay, here's a breakdown of what this Metatrader script does, explained in plain language for someone who isn't a programmer:
Overall Goal:
This script is designed to automatically trade in the Forex market (foreign currency exchange). It looks for specific patterns in price movements and then automatically opens and manages buy or sell orders, aiming to profit from those movements. It is an Expert Advisor and automates technical analysis based trading.
Here's the process step-by-step:
-
Initialization:
- When the script starts, it sets up some initial parameters that you, the user, can adjust. These parameters include things like:
- A "magic number" to identify trades made by this specific script, so it doesn't interfere with other automated trading systems.
- How much the price can "slip" before a trade is executed.
- Trade volumes (lot sizes).
- Take profit and Stop loss values.
- Parameters for indicators that script uses.
- When the script starts, it sets up some initial parameters that you, the user, can adjust. These parameters include things like:
-
Scanning existing trades:
- The script first checks to see if it already has any open trades. If it does, it skips opening a new trade. This avoids opening multiple trades when one is already active.
-
Analyzing market trends (using indicators):
-
The script uses two key indicators to determine the trend:
- Parabolic SAR (SAR): This indicator identifies potential reversals in the price direction. It plots a series of dots on the price chart.
- Kaufman Adaptive Moving Average (KAMA): This is a type of moving average that adapts to price volatility.
-
Large Time Frame Main Trend: This uses the Parabolic SAR and close price on a larger timeframe chart that the user can configure.
-
Normal time frame Trend: This uses the Parabolic SAR and close price on the normal time frame chart.
-
KAMA Trend: The indicator values are compared with the last bar to make buy or sell signals.
-
-
Generating Trade Signals:
-
Buy Signal: Script checks if certain conditions are met:
- KAMA indicator value should be greater than 0.
- The main trend (Large Time Frame) is Up.
- The normal time frame trend is Up.
- Previous candle had a NULL KAMA value.
-
Sell Signal: Similar to the buy signal, the script checks these conditions:
- KAMA indicator value should be greater than 0.
- The main trend (Large Time Frame) is Down.
- The normal time frame trend is Down.
- Previous candle had a NULL KAMA value.
-
-
Money Management (Optional):
- If enabled, the script will automatically adjust the trade size (Lots) based on the available funds in your account and the risk percentage you specify. This helps to manage your risk.
-
Opening a Trade (if signal is present):
- If a buy or sell signal is generated, and the script doesn't already have an open trade, it will open a new trade.
- The order is placed at the current market price.
- It sets initial Stop Loss (to limit potential losses) and Take Profit (to automatically close the trade at a certain profit level) based on the parameters that the user has defined.
- If a buy or sell signal is generated, and the script doesn't already have an open trade, it will open a new trade.
-
Trailing Stop (Optional):
- If enabled, the script will automatically adjust the Stop Loss level of an open trade as the price moves in a favorable direction. This "locks in" profits as the trade moves in your favor.
-
Loop:
- The script constantly repeats steps 2-7, continuously analyzing the market and managing trades.
-
Deinitialization:
- When the script is stopped or removed from the chart, it performs some cleanup, such as deleting objects it has created.
In Summary
The script automates trading decisions. It analyzes the market, looks for specific patterns, and then automatically places and manages trades on your behalf based on the rules and parameters you've set. It tries to identify trends with the SAR indicator and the KAMA, and enter trades accordingly. The risk can be managed by the money management function.
//+------------------------------------------------------------------+
//| SARKAMA_v1.mq4 |
//| Copyright © 2006, Forex-TSD.com |
//| Written by IgorAD,igorad2003@yahoo.co.uk |
//| http://finance.groups.yahoo.com/group/TrendLaboratory |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2006, Forex-TSD.com "
#property link "http://www.forex-tsd.com/"
//---- input parameters
extern string Expert_Name = "---- SARKAMA_v1 ----";
extern int Magic = 10000;
extern int Slippage = 6;
extern string Main_data = " Trade Volume & Trade Method";
extern double Lots = 0.1;
extern double TakeProfit = 0; // Take Profit Value
extern double InitialStop = 150; // Initial Stop Value
extern double TrailingStop = 20; // Trailing Stop Value
extern string SAR_inputs = " Parabolic SAR parameters ";
extern int MainTimeFrame = 1440; // Large Time Frame in min
extern double Step = 0.05; //
extern double Maximum = 0.05; //
extern int BarsBack = 1; //
extern string KAMA_inputs = " Kaufman AMA parameters ";
extern int periodAMA = 9;
extern int nfast = 2;
extern int nslow = 30;
extern double G = 2.0;
extern double dK = 2.0;
extern string MM_inputs = " MoneyManagement by L.Williams ";
extern bool MM = false; // ÌÌ Switch
extern double MMRisk = 0.15; // Risk Factor
extern double MaxLoss = 1000; // Maximum Loss by 1 Lot
int MainTrend=0, Trend=0, MainTrend1=0, Trend1=0, cnt=0, total =0, ticket=0;
double MainSAR, MainClose, SAR, UpKAMA,DnKAMA,UpKAMA1,DnKAMA1,
SellStop,BuyStop,SellProfit,BuyProfit;
bool BuySignal = false, SellSignal = false;
//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init()
{
//----
//----
return(0);
}
// ---- Scan Trades
int ScanTrades()
{
int total = OrdersTotal();
int numords = 0;
for(int cnt=0; cnt<total; cnt++)
{
OrderSelect(cnt, SELECT_BY_POS);
if(OrderSymbol() == Symbol() && OrderType()<=OP_SELLSTOP && OrderMagicNumber() == Magic)
numords++;
}
return(numords);
}
void MainSAR()
{
MainSAR = iSAR(NULL,MainTimeFrame,Step,Maximum,0);
MainClose = iClose(NULL,MainTimeFrame,0);
MainTrend = MainTrend1;
if ( MainSAR < MainClose ) MainTrend = 1;
else if( MainSAR > MainClose ) MainTrend = -1;
MainTrend1 = MainTrend;
}
void SAR()
{
SAR = iSAR(NULL,0,Step,Maximum,BarsBack);
Trend = Trend1;
if ( SAR < Close[BarsBack] ) Trend = 1;
else if( SAR > Close[BarsBack] ) Trend = -1;
Trend1= Trend;
}
void TradeSignal()
{
UpKAMA = iCustom(NULL,0,"Kaufman", periodAMA, nfast, nslow, G, dK, 1,BarsBack);
DnKAMA = iCustom(NULL,0,"Kaufman", periodAMA, nfast, nslow, G, dK, 2,BarsBack);
UpKAMA1 = iCustom(NULL,0,"Kaufman", periodAMA, nfast, nslow, G, dK, 1,BarsBack+1);
DnKAMA1 = iCustom(NULL,0,"Kaufman", periodAMA, nfast, nslow, G, dK, 2,BarsBack+1);
//Print ( " Kama=",UpKAMA," KamaD=",DnKAMA);
BuySignal = (
UpKAMA > 0
&&
MainTrend > 0
&&
Trend > 0
&&
UpKAMA1 == NULL
);
SellSignal= (
DnKAMA > 0
&&
MainTrend < 0
&&
Trend < 0
&&
DnKAMA1 == NULL
);
}
double MoneyManagement ( bool flag, double Lots, double risk, double maxloss)
{
double Lotsi=Lots;
if ( flag ) Lotsi=Lots*NormalizeDouble(Lots*AccountFreeMargin()*MMRisk/MaxLoss,1);
if (Lotsi<0.1) Lotsi=0.1;
return(Lotsi);
}
void TrailStop()
{
for (cnt=0;cnt<OrdersTotal();cnt++)
{
OrderSelect(cnt, SELECT_BY_POS);
int mode=OrderType();
if ( OrderSymbol()==Symbol() && OrderMagicNumber()==Magic)
{
if (mode==OP_BUY)
{
BuyStop = Bid - TrailingStop*Point;
if( OrderOpenPrice() < BuyStop || OrderStopLoss() == 0 )
{
if ( BuyStop > OrderStopLoss() )
{
bool result = OrderModify(OrderTicket(),OrderOpenPrice(),
NormalizeDouble(BuyStop, Digits),
OrderTakeProfit(),0,LightGreen);
if( !result )
{
Print("BUY: OrderModify failed with error #",GetLastError());
}
return(0);
}
}
}
// - SELL Orders
if (mode==OP_SELL)
{
SellStop = Ask + Point * TrailingStop;
if( OrderOpenPrice() > SellStop)
{
if( OrderStopLoss() > SellStop || OrderStopLoss() == 0 )
{
OrderModify(OrderTicket(), OrderOpenPrice(),
NormalizeDouble(SellStop, Digits),
OrderTakeProfit(),0,DarkOrange);
if( !result )
{
Print("SELL: OrderModify failed with error #",GetLastError());
}
return(0);
}
}
}
}
}
}
// ---- Open Sell Orders
void SellOrdOpen()
{
double SellPrice = Bid;
double StopPrice = Ask;
int Mode = OP_SELL;
if (InitialStop > 0) SellStop = StopPrice + InitialStop*Point;
else SellStop = 0;
if (TakeProfit > 0) SellProfit = SellPrice - TakeProfit*Point;
else SellProfit=0;
ticket = OrderSend( Symbol(),Mode,MoneyManagement ( MM, Lots, MMRisk, MaxLoss),
NormalizeDouble(SellPrice , Digits),
Slippage,
NormalizeDouble(SellStop , Digits),
NormalizeDouble(SellProfit, Digits),
"sell",Magic,0,Red);
if(ticket<0)
{
Print("SELL: OrderSend failed with error #",GetLastError());
}
return(0);
}
// ---- Open Buy Orders
void BuyOrdOpen()
{
double BuyPrice = Ask;
double StopPrice = Bid;
int Mode = OP_BUY;
if (InitialStop > 0) BuyStop = StopPrice - InitialStop*Point;
else BuyStop = 0;
if (TakeProfit > 0) BuyProfit= BuyPrice + TakeProfit*Point;
else BuyProfit=0;
ticket = OrderSend(Symbol(),Mode, MoneyManagement ( MM, Lots, MMRisk, MaxLoss),
NormalizeDouble(BuyPrice , Digits),
Slippage,
NormalizeDouble(BuyStop , Digits),
NormalizeDouble(BuyProfit, Digits),
"buy",Magic,0,Blue);
if(ticket<0)
{
Print("BUY : OrderSend failed with error #",GetLastError());
}
return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----
ObjectsDeleteAll();
//----
return(0);
}
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
MainSAR();
SAR();
TradeSignal();
if ( TrailingStop > 0 ) TrailStop();
if (ScanTrades()<1 && BuySignal ) BuyOrdOpen() ;
if (ScanTrades()<1 && SellSignal) SellOrdOpen();
//----
return(0);
} //start()
//+------------------------------------------------------------------+
Comments