This script is designed to automatically trade on the Forex market using the MetaTrader platform. Here's a breakdown of its logic:
1. Initial Setup and Configuration:
- The script starts by defining several settings that control its behavior. These settings are like knobs and switches that you can adjust. Examples include:
- Maximum Trades: The highest number of trades the script is allowed to have open at the same time.
- Pip Distance: The minimum price change required before the script considers opening a new trade.
- Take Profit: The profit level at which a trade will automatically close to secure gains.
- Trailing Stop: A feature that automatically adjusts the stop-loss order (a safety net to limit losses) as the price moves in a favorable direction.
- Initial Stop: The initial stop-loss level for a new trade.
- Lot Size: The initial size of the trades it will open.
- It also defines indicators such as RSI that it will use to trigger a buy or sell.
2. Market Analysis and Decision-Making:
- The script continuously monitors the market using built-in indicators and price data.
- Trend Identification: It looks for signals that suggest whether the market is trending upwards (bullish) or downwards (bearish). It mainly uses a calculation of the current average price compared to the past average price and also calculates the MACD (Moving Average Convergence Divergence) to estimate this trend.
- RSI Calculation: It uses the Relative Strength Index which determines whether the market is considered overbought (likely to fall) or oversold (likely to rise). It also considers a smoothed version of the average price to adjust the RSI.
- Trade Conditions: Based on these analyses, the script determines whether the conditions are right to open a buy or sell trade. A "buy" trade is placed if the script believes the price will go up, and a "sell" trade is placed if it believes the price will go down. It takes into account whether the previous average price is higher or lower than the current price.
3. Trade Execution:
- Opening Trades: If the market analysis indicates a suitable trading opportunity and the script is enabled to trade (based on the settings and current conditions), it will automatically open a new trade (either a buy or sell).
- Trade Management:
- Stop-Loss and Take-Profit: When a trade is opened, the script sets a stop-loss and take-profit level. This helps to manage risk and automatically secure profits.
- Trailing Stop: If enabled, the script will adjust the stop-loss level as the price moves in a favorable direction, allowing the trade to potentially capture more profit while still limiting potential losses.
4. Account Protection:
- Maximum Trades: The script enforces a limit on the maximum number of open trades to prevent excessive risk.
- Profit Protection: It provides a mechanism to partially close an existing trade if a certain amount of overall profit is achieved.
- Balance Control: If the account equity (the overall value of the account including open trades) drops below a certain threshold it will close the position.
5. Order Logic
- It calculates the trend of the market using average calculations and based on this if the trend has a buy or sell indication, it checks if a new bar has been formed and based on this decides to open a buy or sell. Also the script will use a higher lot size in order to open more profitable orders.
In Simple Terms:
Imagine this script as an automated Forex trader that follows a set of rules. It constantly watches the market, analyzes price patterns, and tries to predict whether prices will go up or down. Based on these predictions, it automatically opens buy or sell trades, sets safety nets (stop-loss), and profit targets (take-profit). It also includes some protective measures to limit risk and protect your trading account. The script does not trade at all if the market conditions are not favorable.
//| Copyright 2007, Cocoracas |
//| http://www.algunaweb.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2007, Cocoracas"
#property link "http://www.algunaweb.com"
int MaxTrades = 4;
int Pips = 5;
double TakeProfit = 40;
double TrailingStop = 10;
double InitialStop = 0;
extern string Note1 = "TF 15M";
int MACDTimeFrame = 0;
int SecureProfit = 5;
int AccountProtection = 1;
int OrdersToProtect = 3;
int ReverseCondition = 0;
double FirstOrderLots=0.1;
int OrdersOpened = 0;
int cnt = 0;
double lots = 0.1;
int slippage = 5;
double stoploss = 0;
double takeprofit = 0;
double bprice = 0;
double sprice = 0;
double lotsi = 0;
int type = 0;
int state = 0;
bool EnableTrading = true;
bool allowtrade = false;
double openprice = 0;
int PreviousOrders = 0;
double Profit = 0;
int LastTicket = 0;
int LastType = 0;
double LastClosePrice = 0;
double LastLots = 0;
double PipValue = 0;
string text2 = "";
string text = "";
double lotstmp;
double trade;
double trade1;
int trendtype;
double perdida = 0;
double balance;
double lastbalance = 0;
double curbalance = 0;
//---- input parameters
int RSIOMA = 5;//Original 14
int RSIOMA_MODE = MODE_EMA;
int RSIOMA_PRICE = PRICE_CLOSE;
int Ma_RSIOMA = 13,/*Original 21*/
Ma_RSIOMA_MODE = MODE_EMA;
int BuyTrigger = 80;
int SellTrigger = 20;
int MainTrendLong = 50;
int MainTrendShort = 50;
double RSIBuffer[];
double PosBuffer[];
double NegBuffer[];
double bdn[],bup[];
double sdn[],sup[];
double marsioma[];
//---- buffers
string short_name;
double rel,rel1,negative,positive;
int i;
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
int init()
{
return(0);
}
//+------------------------------------------------------------------+
int deinit()
{
return(0);
}
//+------------------------------------------------------------------+
int start()
{
if (AccountBalance()>curbalance)
curbalance=lastbalance;
double macd = iMACD(NULL,0,5,13,1,PRICE_CLOSE,MODE_MAIN,0);
int counted_bars=IndicatorCounted();
double rel,rel1,negative,positive;
//----
if(Bars<=RSIOMA) return(0);
//---- initial zero
if(counted_bars<1)
for(i=1;i<=RSIOMA;i++) RSIBuffer[Bars-i]=0.0;
//----
i=Bars-RSIOMA-1;
int ma = i;
if(counted_bars>=RSIOMA) i=Bars-counted_bars-1;
while(i>=0)
{
double sumn=0.0,sump=0.0;
if(i==Bars-RSIOMA-1)
{
int k=Bars-2;
//---- initial accumulation
while(k>=i)
{
double cma = iMA(Symbol(),0,RSIOMA,0,RSIOMA_MODE,RSIOMA_PRICE,k);
double pma = iMA(Symbol(),0,RSIOMA,0,RSIOMA_MODE,RSIOMA_PRICE,k+1);
rel=cma-pma;
if(rel>0) sump+=rel;
else sumn-=rel;
k--;
}
positive=sump/RSIOMA;
negative=sumn/RSIOMA;
}
else
{
//---- smoothed moving average
double ccma = iMA(Symbol(),0,RSIOMA,0,RSIOMA_MODE,RSIOMA_PRICE,i);
double ppma = iMA(Symbol(),0,RSIOMA,0,RSIOMA_MODE,RSIOMA_PRICE,i+1);
rel=ccma-ppma;
if(rel>0) sump=rel;
else sumn=-rel;
positive=(PosBuffer[i+1]*(RSIOMA-1)+sump)/RSIOMA;
negative=(NegBuffer[i+1]*(RSIOMA-1)+sumn)/RSIOMA;
}
// Comment(rel);
PosBuffer[i]=positive;
NegBuffer[i]=negative;
if(negative==0.0) RSIBuffer[i]=0.0;
else
{
RSIBuffer[i]=100.0-100.0/(1+positive/negative);
bdn[i] = 0;
bup[i] = 0;
sdn[i] = 0;
sup[i] = 0;
if(RSIBuffer[i]>MainTrendLong)
bup[i] = -10;
if(RSIBuffer[i]<MainTrendShort)
bdn[i] = -10;
if(RSIBuffer[i]<20 && RSIBuffer[i]>RSIBuffer[i+1])
sup[i] = -10;
if(RSIBuffer[i]>80 && RSIBuffer[i]<RSIBuffer[i+1])
sdn[i] = -10;
}
i--;
}
while(ma>=0)
{
marsioma[ma] = iMAOnArray(RSIBuffer,0,Ma_RSIOMA,0,Ma_RSIOMA_MODE,ma);
ma--;
}
//Comment(rel);
if (OrdersTotal()==0)
balance = AccountBalance();
if (lastbalance < curbalance)
FirstOrderLots = AccountBalance()/200;
else
FirstOrderLots = AccountBalance()/4000;
lotsi = FirstOrderLots;
if (lotsi > 50.0) lotsi = 50;
if (lotsi<0.01) lotsi=0.01;
string tripo;
if (rel > 0 && macd > 0) tripo = "compra";
if (rel < 0 && macd < 0) tripo = "vende";
OrdersOpened = 0;
Comment("lastbalance = ",lastbalance,"\ncurbalance = ",curbalance);
//Comment("Tipo de Operacin = ",tripo," Beneficio = ",OrderProfit(),"\nSi haces las operaciones manualmente, no inviertas en la primera operacin ms de ; ",AccountBalance()/4000," Lotes");
for (cnt = 0; cnt < OrdersTotal(); cnt++)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if (OrderSymbol() == Symbol()) OrdersOpened++;
}
PipValue=MarketInfo(Symbol(),MODE_TICKVALUE);
if (PipValue == 0.0) PipValue = 5;
if (PreviousOrders > OrdersOpened)
{
for (cnt = OrdersTotal(); cnt >= 0; cnt--)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
type = OrderType();
if (OrderSymbol() == Symbol())
{
if (type == OP_BUY) OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),slippage,Blue);lastbalance = AccountBalance();
if (type == OP_SELL) OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),slippage,Red);lastbalance = AccountBalance();
//return(0);
}
}
}
PreviousOrders = OrdersOpened;
if (OrdersOpened >= MaxTrades) EnableTrading = false; else EnableTrading = true;
if (openprice == 0.0)
{
for (cnt = 0; cnt < OrdersTotal(); cnt++)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
type = OrderType();
if (OrderSymbol() == Symbol())
{
openprice = OrderOpenPrice();
if (type == OP_BUY) state = 2;
if (type == OP_SELL) state = 1;
}
}
}
//double ma34 = iMA(NULL,PERIOD_M1,2,0,MODE_EMA,PRICE_CLOSE,0);
//double ma89 = iMA(NULL,PERIOD_M1,5,0,MODE_EMA,PRICE_CLOSE,0);
//double sarCurrent = iSAR(NULL,PERIOD_M5,0.009,0.2,0);
//double sarPrevious = iSAR(NULL,PERIOD_M5,0.009,0.2,1);
if (OrdersOpened < 1)
{
state = 3;
if (rel > 0 && macd > 0) state = 2;
if (rel < 0 && macd < 0) state = 1;
if (ReverseCondition == 1)
{
if (state == 1)
{
state = 2;
}
else
{
if (state == 2)
{
state = 1;
}
}
}
}
for (cnt = OrdersTotal(); cnt >= 0; cnt--)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if (OrderSymbol() == Symbol())
{
if (OrderType() == OP_SELL)
{
if (TrailingStop > 0.0)
{
if (OrderOpenPrice() - Ask >= (TrailingStop + (Pips - 3)) * Point)
{
if (OrderStopLoss() > Ask + Point * TrailingStop)
{
OrderModify(OrderTicket(),OrderOpenPrice(),Ask + Point * TrailingStop,OrderClosePrice() - TakeProfit * Point - TrailingStop * Point,800,Purple);
return(0);
}
}
}
}
if (OrderType() == OP_BUY)
{
if (TrailingStop > 0.0)
{
if (Bid - OrderOpenPrice() >= (TrailingStop + (Pips - 3)) * Point)
{
if (OrderStopLoss() < Bid - Point * TrailingStop)
{
OrderModify(OrderTicket(),OrderOpenPrice(),Bid - Point * TrailingStop,OrderClosePrice() + TakeProfit * Point + TrailingStop * Point,800,Yellow);
return(0);
}
}
}
}
}
}
Profit = 0;
LastTicket = 0;
LastType = 0;
LastClosePrice = 0;
LastLots = 0;
for (cnt = 0; cnt < OrdersTotal(); cnt++)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if (OrderSymbol() == Symbol())
{
LastTicket = OrderTicket();
if (OrderType() == OP_BUY) LastType = 0;
if (OrderType() == OP_SELL) LastType = 1;
LastClosePrice = OrderClosePrice();
LastLots = OrderLots();
if (LastType == 0)
{
if (OrderClosePrice() < OrderOpenPrice()) Profit -= (OrderOpenPrice() - OrderClosePrice()) * OrderLots() / Point;
if (OrderClosePrice() > OrderOpenPrice()) Profit += (OrderClosePrice() - OrderOpenPrice()) * OrderLots() / Point;
}
if (LastType == 1)
{
if (OrderClosePrice() > OrderOpenPrice()) Profit -= (OrderClosePrice() - OrderOpenPrice()) * OrderLots() / Point;
if (OrderClosePrice() < OrderOpenPrice()) Profit += (OrderOpenPrice() - OrderClosePrice()) * OrderLots() / Point;
}
}
}
Profit = Profit * PipValue;
text = "Profit: $" + DoubleToStr(Profit,2) + " +/-";
if ((OrdersOpened >= 3))
{
if (AccountEquity()/AccountBalance()>=1)
{
OrderClose(LastTicket,LastLots,LastClosePrice,slippage,Yellow);
EnableTrading = false;
return(0);
}
}
if ((OrdersOpened >= 4))
{
if (AccountEquity()/AccountBalance()<=0.90)
{
curbalance=AccountEquity();
OrderClose(LastTicket,LastLots,LastClosePrice,slippage,Yellow);
EnableTrading = false;
return(0);
}
}
if (!IsTesting())
{
if (state == 3)
text2 = "No conditions to open trades";
else
text2 = " ";
}
if ((state == 1) && EnableTrading)
{
if ((Bid - openprice >= Pips * Point) || (OrdersOpened < 1))
{
sprice = Bid;
openprice = 0;
if (TakeProfit == 0.0)
takeprofit = 0;
else
takeprofit = sprice - TakeProfit * Point;
if (InitialStop == 0.0)
stoploss = 0;
else
stoploss = sprice + InitialStop * Point;
if (OrdersOpened != 0)
{
lots = lotsi;
for (cnt = 1; cnt <= OrdersOpened; cnt++)
{
if (MaxTrades>12) { lots=NormalizeDouble(lots*3,2); }
else { lots=NormalizeDouble(lots*3,2); }
}
}
else
{
lots = lotsi;
}
if (NewBar() == true) allowtrade=true;//is for one trade for each bar
if (allowtrade)//entry
{
if (lots > 50.0) lots = 50;
lastbalance = AccountBalance();
OrderSend(Symbol(),OP_SELL,lots,sprice,slippage,stoploss,takeprofit,0,0,0,Red);
allowtrade=false;
return(0);
}
}
}
if ((state == 2) && EnableTrading)
{
if ((openprice - Ask >= Pips * Point) || (OrdersOpened < 1))
{
bprice = Ask;
openprice = 0;
if (TakeProfit == 0.0) takeprofit = 0; else takeprofit = bprice + TakeProfit * Point;
if (InitialStop == 0.0) stoploss = 0; else stoploss = bprice - InitialStop * Point;
if (OrdersOpened != 0)
{
lots = lotsi;
for (cnt = 1; cnt <= OrdersOpened; cnt++)
{
if (MaxTrades>12) { lots=NormalizeDouble(lots*3,2); }
else { lots=NormalizeDouble(lots*3,2); }
}
}
else
{
lots = lotsi;
}
if (NewBar() == true) allowtrade=true;//is for one trade for each bar
if (allowtrade)//entry
{
if (lots > 50.0) lots = 50;
lastbalance = AccountBalance();
OrderSend(Symbol(),OP_BUY,lots,bprice,slippage,stoploss,takeprofit,0,0,0,Blue);
allowtrade=false;
return(0);
}
}
}
return(0);
}
bool NewBar()//is for one trade for each bar
{
static datetime lastbar = 0;
datetime curbar = Time[0];
if(lastbar!=curbar)
{
lastbar=curbar;
return (true);
}
else
{
return(false);
}
}
Comments