st+L+2stor-V1-1
Download scriptThis script is an automated trading program designed to operate within the MetaTrader platform. Its primary goal is to automatically open and close trading positions (buy or sell) based on a specific set of technical indicators. Here's a breakdown of how it works:
1. Initialization:
- When the script starts, it opens a file called "StarterDebug.csv" to record its actions for later analysis. It writes a header row indicating the data it will be logging, such as time, trade type, and values of the indicators.
2. Calculating Trade Size:
- Before opening a trade, the script determines the appropriate trade size (lot size) to use. It aims to risk a certain percentage of the account's free margin (the money available for trading).
- It also considers past losing trades. If there's a series of consecutive losses, it reduces the lot size in an attempt to minimize further losses.
- The lot size is also capped to a maximum and minimum value.
3. Technical Indicators:
- The script relies on several technical indicators to make its trading decisions:
- Laguerre RSI: This indicator is used to determine overbought or oversold conditions in the market.
- CCI (Commodity Channel Index): The CCI measures the current price level relative to an average price level over a given period of time. It helps identify when an asset is overbought or oversold.
- Moving Average (MA): This indicator calculates the average price of an asset over a specific period. The script uses it to identify the trend direction.
- Each indicator has customizable parameters that affect its sensitivity and responsiveness.
4. Trading Logic (Opening Positions):
- The script constantly monitors the market and the values of its indicators. It uses a combination of conditions based on these indicators to decide whether to open a buy (long) or sell (short) position.
- Buy (Long) Conditions:
- The Laguerre indicator must signal a specific condition (0).
- The current moving average must be higher than the previous one by a certain amount. This indicates an upward trend.
- The CCI must be increasing, indicating rising momentum.
- The CCI must have crossed a specific level from below, indicating a potential buying opportunity.
- The percentage change in CCI must be greater than a set threshold.
- Sell (Short) Conditions:
- The Laguerre indicator must signal a specific condition (1).
- The current moving average must be lower than the previous one by a certain amount. This indicates a downward trend.
- The CCI must be decreasing, indicating falling momentum.
- The CCI must have crossed a specific level from above, indicating a potential selling opportunity.
- The percentage change in CCI must be greater than a set threshold.
- If all the conditions for a buy or sell are met, the script opens a trade in the corresponding direction, using the calculated lot size. It can optionally set a stop-loss order to limit potential losses.
- The program logs the details of the trade, along with the indicator values, to the "StarterDebug.csv" file.
5. Trading Logic (Closing Positions):
- The script also monitors open positions. It closes a position based on the following conditions:
- Laguerre Exit: It monitors the Laguerre RSI, when the indicator reaches certain level triggers the closing of the position.
- Stop Loss: If the price moves against the position by a certain amount (defined by the "Stop" parameter), the script closes the position to limit losses.
6. Order Management:
- The script is designed to manage only its own trades. It uses a "Magic Number" to identify trades opened by this particular script and avoids interfering with trades opened manually or by other automated systems.
7. Deinitialization:
- When the script is stopped or removed from the chart, it closes the "StarterDebug.csv" file, ensuring that all data is saved.
//+------------------------------------------------------------------+
//| Starter.mq4 |
//| Copyright © 2005, MetaQuotes Software Corp. |
//| http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2005, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net"
//#include <Tracert.mqh>
extern double Lots = 0.1;
extern double MaximumRisk = 0.03;
extern double DecreaseFactor = 3;
extern int Stop = 10;
extern int SL = 0; //Äëÿ "ýñòåòîâ" èç ôîðóìó StopLoss
//extern double Lots = 4;
//Ïàðàìåòðû Laguerre
extern double GammaP = 0.7; // Íåêàÿ "Ãàììà" èç ïàðàìåòðîâ "Laguerre"
extern double StopL = 0.1; // "Ïîðîã" "Laguerre" äëÿ çàêðûòèÿ ïîçèöèè
extern int ShftL = 0; // Áàð, íà êîòîðîì ðàññ÷èòûâàåòñÿ "Laguerre"
//Ïàðàìåòðû CCI
extern int CCIperiod = 14; // Ñîáñòâåííî ïåðèîä CCI
extern int TypeCCI = 0; // "Öåíîâûå êîíñòàíòû" äëÿ ðàñ÷òåèà CCI
// 0-Close, 1-Open, 2-High, 3-Low, 4-Median,
// 5-Typical, 6-WEIGHTED
extern int DAlpha = 0; // Äåëüòà CCI - "ïîðîã èçìåíåíèÿ ñêîðîñòè CCI"
// â ïðîöåíòàõ
extern int CCILevel = 100; // Êëàññè÷åñêè - óðîâåíü, êîòîðûé äîëæíà
// ïåðåñå÷ü CCI, ÷òîáû äàòü ñèãíàë.
// Êëàññèêà +/-100, 0, â îðèãèíàëüíîì
// starter'å +/-5. ß çàêîììåíòèðîâàë, ò.ê.....
extern int ShftA1 = 0; // Áàð äëÿ ðàñ÷åòà "òåêóùåé" CCI
extern int ShftA2 = 1; // Áàð äëÿ ðàñ÷åòà "ïðåäûäóùåé" CCI
//Ïàðàìåòðû MA
extern double MAPeriod = 120; // Ñîáñòâåííî ïåðèîä MA
extern int TypeMA = 0; // "Öåíîâûå êîíñòàíòû" äëÿ ðàñ÷òåèà MA
// 0-Close, 1-Open, 2-High, 3-Low, 4-Median,
// 5-Typical, 6-WEIGHTED
extern int ShftMA = 0; // Áàð äëÿ ðàñ÷åòà "òåêóùåé" MA (Áàð äëÿ
// "ïðåäûäóùåé" MA = ShftMA+1 (â îòëè÷èè îò CCI))
extern double DeltaMA = 0.1; // Äåëüòà MA ("òåêóùåãî" è "ïðåäûäóùåãî" áàðà) â "ïèïñàõ"
//MagicNubber
extern int MagicNumber = 20051016; // ß âñåãäà âûíîøó, ÷òîáû ìîæíî áûëî,
// ÍÀÏÐÈÌÅÐ, òîðãîâàòü íà îäíîé ïàðå
// ñ ðàçíûìè ïàðàìåòðàìè
int handle;
//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init()
{
//----
handle = FileOpen("StarterDebug.csv", FILE_CSV | FILE_WRITE);
FileWrite(handle, "Time[0]", "TradeType", "Laguerre", "MA",
"MA1", "DMA", "Alpha1", "Alpha2", "DAlpha");
//----
return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----
FileClose(handle);
//----
return(0);
}
//+------------------------------------------------------------------+
//| Calculate optimal lot size |
//+------------------------------------------------------------------+
double LotsOptimized()
{
double lot = Lots;
int orders = HistoryTotal(); // history orders total
int losses = 0; // number of losses orders without a break
//---- select lot size
lot = NormalizeDouble(AccountFreeMargin()*MaximumRisk / 500, 1);
//---- calcuulate number of losses orders without a break
if(DecreaseFactor > 0)
{
for(int i = orders - 1; i >= 0; i--)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_HISTORY) == false)
{
Print("Error in history!");
break;
}
//----
if(OrderSymbol() != Symbol() || OrderType() > OP_SELL)
continue;
//----
if(OrderProfit() > 0)
break;
//----
if(OrderProfit() < 0)
losses++;
}
//----
if(losses > 1)
lot = NormalizeDouble(lot - lot*losses / DecreaseFactor, 1);
}
//---- return lot size
if(lot < 1)
lot = 1;
//----
if(lot > 1000)
lot = 1000;
return(lot);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
double LaGuerre(double gamma, int shift)
{
double RSI;
double L0[100];
double L1[100];
double L2[100];
double L3[100];
double CU, CD;
//----
for(int i = shift + 99; i >= shift; i--)
{
L0[i] = (1.0 - gamma)*Close[i] + gamma*L0[i+1];
L1[i] = -gamma*L0[i] + L0[i+1] + gamma*L1[i+1];
L2[i] = -gamma*L1[i] + L1[i+1] + gamma*L2[i+1];
L3[i] = -gamma*L2[i] + L2[i+1] + gamma*L3[i+1];
CU = 0;
CD = 0;
if(L0[i] >= L1[i])
CU = L0[i] - L1[i];
else
CD = L1[i] - L0[i];
//----
if(L1[i] >= L2[i])
CU = CU + L1[i] - L2[i];
else
CD = CD + L2[i] - L1[i];
//----
if(L2[i] >= L3[i])
CU = CU + L2[i] - L3[i];
else
CD = CD + L3[i] - L2[i];
//----
if(CU + CD != 0)
RSI = CU / (CU + CD);
}
return(RSI);
}
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
double Laguerre;
double SLstop;
double Alpha1, Alpha2;
double MA, MA1;
//+-- double Juice;
int cnt, ticket, RealTotal, total;
// Laguerre=iCustom(NULL, 0, "Laguerre", 0, 0);
Laguerre = LaGuerre(GammaP, 0);
Alpha1 = iCCI(NULL, 0, CCIperiod, TypeCCI, ShftA1);
Alpha2 = iCCI(NULL, 0, CCIperiod, TypeCCI, ShftA2);
MA = iMA(NULL, 0, MAPeriod, 0, MODE_EMA, TypeMA, ShftMA);
MA1 = iMA(NULL, 0, MAPeriod, 0, MODE_EMA, TypeMA, ShftMA + 1);
//+-- Juice=iCustom(NULL,0,"Juice",0,0);
total = OrdersTotal();
// Èùåì ðåàëüíîå ÷èëî òîðãîâûõ îðäåðîâ äëÿ íàøåãî MagicNumber íà íàøåé ïàðå,
// ÷òîáû äàòü òîðãîâàòü ñåáå è äðóãèì ñîâåòíèêàì
for(cnt = 0; cnt < total; cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderMagicNumber() == MagicNumber && OrderSymbol() == Symbol())
RealTotal = RealTotal + 1;
}
if(RealTotal < 1)
{
// no opened orders identified
if(AccountFreeMargin() < (1000*Lots))
{
Print("We have no money. Free Margin = ", AccountFreeMargin());
return(0);
}
// check for long position (BUY) possibility
if(//Èç "îðèãèíàëà"
(Laguerre==0) &&
//Íå ïðîñòî ðîñò MA, íî è ìèíèìóì íåêîòîðóþ äåëüòó
(MA - MA1 > DeltaMA * Point) &&
//Ðîñò CCI
(Alpha2 < Alpha1) &&
//Ïåðåñå÷åíèå íåêîòîðîãî óðîâíÿ +/-100, 0 "Ñíèçó-ââåðõ"
(Alpha1 > -1 * CCILevel && Alpha2 < -1 * CCILevel) &&
// && // îðèãèíàëå (åñëè ÷åñòíî - íå ïîíÿë. ÈÌÕÎ èìåëîñü ââèäó ïåðåñå÷åíèå
// èëè "ïîäõîä" ê) 0, íî, åñëè ñìîòðåòü îòëàäî÷íûé ôàéë, òî òàì ....
// (Alpha1 < -5)
//Ðîñò CCI â % áîëüøå ïîðîãà
(MathAbs(Alpha1 - Alpha2) / MathMax(MathAbs(Alpha1), MathAbs(Alpha2))*100 > DAlpha)
) //+-- && Juice>JuiceLevel)
{
FileWrite(handle, "Buy", Time[0], Laguerre, MA, MA1, MA-MA1, Alpha1, Alpha2,
MathAbs(Alpha1 - Alpha2) / MathMax(MathAbs(Alpha1),
MathAbs(Alpha2))*100 );
FileFlush(handle);
//Äëÿ "ýñòåòîâ" StopLoss
if(SL == 0)
SLstop = 0;
else
SLstop = Ask - SL * Point;
ticket = OrderSend(Symbol(), OP_BUY, LotsOptimized(), Ask, 3, SLstop, 0,
"starter", MagicNumber, 0, Green);
}
// check for short position (SELL) possibility
if(//Èç "îðèãèíàëà"
(Laguerre==1) &&
//Íå ïðîñòî ïàäåíèå MA, íî è ìèíèìóì íåêîòîðóþ äåëüòó
(MA - MA1 < -1 * DeltaMA * Point) &&
//Ïàäåíèå CCI
(Alpha2 > Alpha1) &&
//Ïåðåñå÷åíèå íåêîòîðîãî óðîâíÿ +/-100, 0 "Ñâåðõó-âíèç"
(Alpha1 < CCILevel && Alpha2 > CCILevel)
// && // îðèãèíàëå (åñëè ÷åñòíî - íå ïîíÿë. ÈÌÕÎ èìåëîñü ââèäó ïåðåñå÷åíèå (èëè "ïîäõîä" ê) 0, íî, åñëè ñìîòðåòü îòëàäî÷íûé ôàéë, òî òàì ....
// (Alpha1 > 5)
&& //Ðîñò CCI â % áîëüøå ïîðîãà
(MathAbs(Alpha1 - Alpha2)/MathMax(MathAbs(Alpha1),MathAbs(Alpha2))*100 > DAlpha)
) //+-- && Juice>JuiceLevel)
{
FileWrite(handle, "Sell", Time[0], Laguerre, MA, MA1, MA-MA1, Alpha1, Alpha2, MathAbs(Alpha1 - Alpha2)/MathMax(MathAbs(Alpha1),MathAbs(Alpha2))*100 );
FileFlush(handle);
//Äëÿ "ýñòåòîâ" StopLoss
if (SL == 0)
SLstop = 0;
else
SLstop = Bid + SL * Point;
ticket=OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,SLstop,0,"starter",MagicNumber,0,Red);
}
}
// it is important to enter the market correctly,
// but it is more important to exit it correctly...
for(cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderType()<=OP_SELL && // check for opened position
OrderSymbol()==Symbol() && // check for symbol
OrderMagicNumber() == MagicNumber) // check for MagicNumber (×òîáû ðóëèòü òîëüêî ñâîèìè ñäåëêàìè ñâîåãî ñîâåòíèêà)
{
if(OrderType()==OP_BUY) // long position is opened
{
// should it be closed?
if(Laguerre>1-StopL)
{
OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet); // close position
return(0); // exit
}
// check for stop
if(Stop>0)
{
if(Bid-OrderOpenPrice()>Point*Stop)
{
OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet); // close position
return(0);
}
}
}
else // go to short position
{
// should it be closed?
if(Laguerre<StopL)
{
OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet); // close position
return(0); // exit
}
// check for stop
if(Stop>0)
{
if(OrderOpenPrice()-Ask>Point*Stop)
{
OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet); // close position
return(0);
}
}
}
}
}
return(0);
}
//+------------------------------------------------------------------+
Profitability Reports
Expected payoff
Average expected payoff across the available backtests for each symbol.
Comments