Here's a breakdown of what the script does, explained without technical jargon:
Overall Idea:
This script is designed to automatically trade on the foreign exchange market (Forex) using a strategy based on identifying when the price of a currency pair has moved too far in one direction and is likely to reverse. It uses a "moving average" to help determine these overextended conditions and places trades accordingly. If a trade starts to lose money, it adds another trade to try and improve the overall position.
Key Components and How They Work:
-
Moving Average (MA):
- Imagine calculating the average price of a currency over a certain period (e.g., 10 days). This is a moving average. It helps smooth out the price fluctuations and identify the general trend.
- The script calculates a 10-day average price of a currency pair. The script uses the open price to calculate this moving average and can be adjusted to use other time frames.
-
"Envelope" or Channel:
- The script creates a channel around the moving average. It does this by shifting the moving average line up by a small percentage (e.g., 2%) and down by the same percentage. This creates an upper and lower band around the average price.
- Think of these bands as representing areas where the price is considered "high" or "low" relative to its recent average.
-
Trading Signals:
- The script watches for the currency price to break outside of these upper or lower bands.
- If the price goes above the upper band, the script assumes the currency is overbought and will likely fall. It then initiates a "sell" trade (betting the price will go down).
- If the price goes below the lower band, the script assumes the currency is oversold and will likely rise. It then initiates a "buy" trade (betting the price will go up).
- The script watches for the currency price to break outside of these upper or lower bands.
-
Averaging Down (or Up):
- If the initial trade goes against the script's prediction (i.e., the price moves in the wrong direction), the script opens another trade in the same direction.
- This is called "averaging." The idea is that by adding more trades at a worse price, the average entry price for the overall position improves. If the price eventually reverses, the overall position becomes profitable more quickly.
-
Take Profit and Stop Loss:
- Take Profit: This is a target price at which the script automatically closes the trade to lock in a profit.
- Stop Loss: This is a price level at which the script automatically closes the trade to limit losses if the price continues to move against the prediction. The stop loss is based on an total loss of all open positions.
-
Lot Size:
- This determines the size of the trades. A larger lot size means more potential profit (but also more potential loss).
-
Magic Number:
- This is a unique identifier used to distinguish trades made by this script from trades made by other automated systems or manual trading.
-
Slippage:
- This allows the trade to be executed at a slightly different price than requested if the market is moving quickly.
-
PipStep and IncreasementType: *This is the amount that the trade needs to move against the trend, after which a second trade will be opened to average out the positions to attempt to generate profits when the price reverts.
Important Considerations:
- Risk: This type of strategy can be risky, especially the "averaging" aspect. If the price continues to move strongly in one direction, the script can open multiple losing trades, potentially leading to significant losses.
- Market Conditions: The script's effectiveness likely depends on the specific currency pair and prevailing market conditions. It might work well in some situations but perform poorly in others.
- Customization: The script has several adjustable parameters (e.g., moving average length, percentage deviation, take profit, stop loss) that can be tweaked to potentially improve performance or adapt to different market environments.
- Stop loss modification The script monitors the current positions and recalculates the stop losses based on a percentage of the total funds in the account.
In short, this script tries to profit from short-term price reversals in the Forex market by identifying overbought/oversold conditions and using an averaging strategy to manage losing trades.
/*-----------------------------+
| |
| Shared by www.Aptrafx.com |
| |
+------------------------------*/
//+-----------------------------------------------------------------------------+
//| Firebird v0.63 - MA envelope exhaustion system |
//+-----------------------------------------------------------------------------+
#property copyright "Copyright © 2005, TraderSeven"
#property link "TraderSeven@gmx.net"
// \\|// +-+-+-+-+-+-+-+-+-+-+-+ \\|//
// ( o o ) |T|r|a|d|e|r|S|e|v|e|n| ( o o )
// ~~~~oOOo~(_)~oOOo~~~~ +-+-+-+-+-+-+-+-+-+-+-+ ~~~~oOOo~(_)~oOOo~~~~
// Firebird calculates a 10 day SMA and then shifts it up and down 2% to for a channel.
// For the calculation of this SMA either close (more trades) or H+L (safer trades) is used.
// When the price breaks a band a postion in the opposite of the current trend is taken.
// If the position goes against us we simply open an extra position to average.
// 50% of the trades last a day. 45% 2-6 days 5% longer or just fail.
//
//01010100 01110010 01100001 01100100 01100101 01110010 01010011 01100101 01110110 01100101 01101110
// Credits fly to:
// Vooch for the backtesting fix.
// Hugues Du Bois for the multi currency code.
// Jackie Griffin for some debugging.
// Many people in the MT forum for testing and feedback
/*
EURUSD - IBFX
MA_length=32
MA_timeframe=30
MAtype=0
Percent=0.15000000
TradeOnFriday=1
slip=100
Lots=0.30000000
TakeProfit=41
Stoploss=100
PipStep=2
IncreasementType=0.00000000
MagicNumber=12345
GBPUSD
MA_length=18
MA_timeframe=30
MAtype=0
Percent=0.25000000
TradeOnFriday=1
slip=100
Lots=0.30000000
TakeProfit=27
Stoploss=100
PipStep=5
IncreasementType=0.00000000
MagicNumber=12345
*/
//----------------------- USER INPUT
extern int MA_length = 10;
extern int MA_timeframe = 30; // hdb did I add this ? lol
extern int MAtype=0;//0=close, 1=HL
extern double Percent = 0.1;
extern int TradeOnFriday =1; // >0 trades on friday
extern int slip = 100;//exits only
extern double Lots = 0.3;
extern int TakeProfit = 30;
extern int Stoploss = 2000;// total loss on all open positions in pips
//extern double TrailingStop = 5;
extern int PipStep = 30;//if position goes this amount of pips against you add another.
extern double IncreasementType =0;//0=just add every PipStep, >0 =OrdersToal()^x *Pipstep
extern int MagicNumber=12345;
double Stopper=0;
double KeepStopLoss=0;
double KeepAverage;
double dummy;
double spread=0;
double CurrentPipStep;
int OrderWatcher=0;
//----------------------- MAIN PROGRAM LOOP
int start(){
if(Symbol()=="EURUSDm") {// - IBFX
MA_length=32;
MA_timeframe=30;
MAtype=0;
Percent=0.15000000;
TradeOnFriday=1;
slip=100;
Lots=0.30000000;
TakeProfit=41;
Stoploss=100;
PipStep=2;
IncreasementType=0.00000000;
MagicNumber=12345;}
if(Symbol()=="GBPUSDm") {
MA_length=18;
MA_timeframe=30;
MAtype=0;
Percent=0.25000000;
TradeOnFriday=1;
slip=100;
Lots=0.30000000;
TakeProfit=27;
Stoploss=100;
PipStep=5;
IncreasementType=0.00000000;
MagicNumber=12345;}
double PriceTarget;
double AveragePrice;
int OpeningDay;
//----------------------- CALCULATE THE NEW PIPSTEP
CurrentPipStep=PipStep;
if(IncreasementType>0)
{
CurrentPipStep=MathSqrt(OrdersTotal())*PipStep;
CurrentPipStep=MathPow(OrdersTotal(),IncreasementType)*PipStep;
}
//-----------------------
int Direction=0;//1=long, 11=avoid long, 2=short, 22=avoid short
if (Day()!=5 || TradeOnFriday >0)
{
int cnt=0, total;
int myTotal =0; // hdb
total=OrdersTotal();
if(total==0) OpeningDay=DayOfYear();
for(cnt=0;cnt<total;cnt++)
{
if ( (OrderSymbol()==Symbol()) && (OrderMagicNumber()==MagicNumber) ) // hdb - only symbol and magic
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
double LastPrice=OrderOpenPrice();
myTotal = myTotal +1; // hdb - count of relevant trades
}
}
// OrderSelect(total, SELECT_BY_POS, MODE_TRADES); // removed hdb
/////////////////////////////////////////////////////////////////////////////////////////
// BACKTESTER FIX: DO NOT PLACE AN ORDER IF WE JUST CLOSED
// AN ORDER WITHIN Period() MINUTES AGO
/////////////////////////////////////////////////////////////////////////////////////////
datetime orderclosetime;
string rightnow;
int rightnow2;
int TheHistoryTotal=HistoryTotal();
int difference;
int flag=0;
for(cnt=0;cnt<TheHistoryTotal;cnt++)
{
if(OrderSelect(cnt,SELECT_BY_POS,MODE_HISTORY)==true)
{
if ( (OrderSymbol()==Symbol()) && (OrderMagicNumber()==MagicNumber) ) // hdb - only symbol and magic
{
orderclosetime=OrderCloseTime();
rightnow=Year()+"-"+Month()+"-"+Day()+" "+Hour()+":"+Minute()+":"+Seconds();
rightnow2=StrToTime(rightnow);
difference=rightnow2-orderclosetime;
if(Period()*60*2>difference)
{ // At least 2 periods away!
flag=1; // Throw a flag
break;
}
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////
if(flag!=1)
{
//----------------------- PREVIOUS OPEN PRICE
OrderWatcher=0;
total=OrdersTotal();
for(cnt=(total-1);cnt>=0;cnt--){
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
// Print("ordersymbol = ", OrderSymbol(), " OrderOpenPrice= ", DoubleToStr(OrderOpenPrice(), 10));
if ( OrderSymbol()==Symbol()) // && (OrderMagicNumber()==MagicNumber) ) // hdb - only symbol and magic
{
LastPrice=OrderOpenPrice();
Comment("LastPrice= ",DoubleToStr(LastPrice, 10));
// Print("cnt= ", cnt, " ordersymbol = ", OrderSymbol(), " OrderOpenPrice= ", DoubleToStr(OrderOpenPrice(), 10), " lastprice= ",DoubleToStr(LastPrice, 10 ));
break;
}
}
//Print("ordersymbol = ", OrderSymbol(), " OrderOpenPrice= ", DoubleToStr(OrderOpenPrice(), 10), " lastprice= ",DoubleToStr(LastPrice, 10 ));
//----------------------- ENTER POSITION BASED ON OPEN
if(MAtype==0)
{
double myMA =iMA(NULL,MA_timeframe,MA_length,0,MODE_SMA,PRICE_OPEN,0);
// Print(" Top, Bid ",myMA*(1+Percent/100)," ",Bid);
// if((myMA*(1+Percent/100))<Bid) Print(" Top, Bid ",myMA*(1+Percent/100)," ",Bid);
if((myMA*(1+Percent/100))<Bid && Direction!=22 && (Bid>=(LastPrice+(CurrentPipStep*Point))||total==0)) // Go SHORT -> Only sell if >= 30 pips above previous position entry
{
OrderSend(Symbol(),OP_SELL,Lots,Bid,slip,Bid+(Stoploss*Point),Bid-(TakeProfit*Point),0,0,Red);
OrderWatcher=1;
Direction=2;
}
if((myMA*(1-Percent/100))>Ask && Direction!=11 && (Ask<=(LastPrice-(CurrentPipStep*Point))||total==0)) // Go LONG -> Only buy if >= 30 pips below previous position entry
{
OrderSend(Symbol(),OP_BUY,Lots,Ask,slip,Ask-(Stoploss*Point),Ask+(TakeProfit*Point),0,0,Blue);
OrderWatcher=1;
Direction=1;
}
}
//----------------------- ENTER POSITION BASED ON HIGH/LOW
if(MAtype==1)
{
if((iMA(NULL,MA_timeframe,MA_length,0,MODE_SMA,PRICE_HIGH,0)*(1+Percent/100))<Bid && Direction!=22 && (Bid>=(LastPrice+(CurrentPipStep*Point))||total==0)) // Go SHORT -> Only sell if >= 30 pips above previous position entry
{
OrderSend(Symbol(),OP_SELL,Lots,Bid,slip,Bid+(Stoploss*Point),Bid-(TakeProfit*Point),0,0,Red);
OrderWatcher=1;
Direction=2;
}
if((iMA(NULL,MA_timeframe,MA_length,0,MODE_SMA,PRICE_LOW,0)*(1-Percent/100))>Ask && Direction!=11 && (Ask<=(LastPrice-(CurrentPipStep*Point))||total==0)) // Go LONG -> Only buy if >= 30 pips below previous position entry
{
OrderSend(Symbol(),OP_BUY,Lots,Ask,slip,Ask-(Stoploss*Point),Ask+(TakeProfit*Point),0,0,Blue);
OrderWatcher=1;
Direction=1;
}
}
} // end of flag test
//----------------------- CALCULATE AVERAGE OPENING PRICE
total=OrdersTotal();
AveragePrice=0;
int myOrderType = -1; // hdb
myTotal = 0; // hdb - count of relevant trades
if(total>1 && OrderWatcher==1)
{
for(cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if ( (OrderSymbol()==Symbol()) && (OrderMagicNumber()==MagicNumber) ) // hdb - only symbol and magic
{
AveragePrice=AveragePrice+OrderOpenPrice();
myOrderType = OrderType(); // hdb - keep order type
myTotal = myTotal +1; // hdb - count of relevant trades
}
}
AveragePrice=AveragePrice/MathMax(myTotal,1); // hdb myTotal
}
//----------------------- RECALCULATE STOPLOSS & PROFIT TARGET BASED ON AVERAGE OPENING PRICE
// OrderSelect(0, SELECT_BY_POS, MODE_TRADES); // hdb removed
if(myOrderType==OP_BUY && OrderWatcher==1 && myTotal>1) // Calculate profit/stop target for long
{
PriceTarget=AveragePrice+(TakeProfit*Point);
Stopper=AveragePrice-(((Stoploss*Point)/myTotal));
}
if(myOrderType==OP_SELL && OrderWatcher==1 && myTotal>1) // Calculate profit/stop target for short
{
PriceTarget=AveragePrice-(TakeProfit*Point);
Stopper=AveragePrice+(((Stoploss*Point)/myTotal));
}
Comment("AveragePrice", AveragePrice);
//----------------------- IF NEEDED CHANGE ALL OPEN ORDERS TO THE NEWLY CALCULATED PROFIT TARGET
//if(OrderWatcher==1 && myTotal>1)// check if average has really changed
//if(OrderWatcher==1 && myTotal>1)// check if average has really changed
// {
total=OrdersTotal();
for(cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if ( (OrderSymbol()==Symbol()) &&
(OrderMagicNumber()==MagicNumber) ) // hdb - only symbol and magic
{
OrderModify(OrderTicket(),0,Stopper,PriceTarget,0,Yellow);//set all positions to averaged levels
}
}
// }
//Comment("PriceTarget: ",PriceTarget," AveragePrice: ",AveragePrice," Total: ",total);
//----------------------- KEEP TRACK OF STOPLOSS TO AVOID RUNAWAY MARKETS
// Sometimes the market keeps trending so strongly the system never reaches it's target.
// This means huge drawdown. After stopping out it falls in the same trap over and over.
// The code below avoids this by only accepting a signal in teh opposite direction after a SL was hit.
// After that all signals are taken again. Luckily this seems to happen rarely.
if (OrdersTotal()>0)
{
myOrderType = -1; // hdb
myTotal = 0; // hdb - count of relevant trades
total=OrdersTotal();
for(cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if ( (OrderSymbol()==Symbol()) && (OrderMagicNumber()==MagicNumber) ) // hdb - only symbol and magic
{
KeepStopLoss=OrderStopLoss();
AveragePrice=AveragePrice+OrderOpenPrice();
myTotal = myTotal +1; // hdb - count of relevant trades
myOrderType = OrderType(); // hdb - keep order type
}
}
AveragePrice=AveragePrice/MathMax(myTotal,1); // hdb myTotal
KeepAverage=AveragePrice;
Direction =0;
if(myOrderType==OP_BUY)
{ Direction=1; } //long
else
{ if (myOrderType==OP_SELL) Direction=2; }//short
}
if(KeepStopLoss!=0)
{
spread=MathAbs(KeepAverage-KeepStopLoss)/2;
dummy=(Bid+Ask)/2;
if (KeepStopLoss<(dummy+spread) && KeepStopLoss>(dummy-spread))
{
// a stoploss was hit
if(Direction==1) Direction=11;// no more longs
if(Direction==2) Direction=22;// no more shorts
}
KeepStopLoss=0;
}
}
}
//----------------------- TO DO LIST
// 1st days profit target is the 30 pip line *not* 30 pips below average as usually. -----> Day()
// Trailing stop -> trailing or S/R or pivot target
// Realistic stop loss
// Avoid overly big positions
// EUR/USD 30 pips / use same value as CurrentPipStep
// GBP/CHF 50 pips / use same value as CurrentPipStep
// USD/CAD 35 pips / use same value as CurrentPipStep
//----------------------- OBSERVATIONS
// GBPUSD not suited for this system due to not reversing exhaustions. Maybe use other types of MA
// EURGBP often sharp reversals-> good for trailing stops?
// EURJPY deep pockets needed.
Comments