TimeBreakExpert_v2
Download scriptThis automated trading script is designed to manage currency trades based on specific time windows, utilizing a combination of "pending orders" and active trade management. Instead of constantly trying to enter the market, it waits for specific pre-defined moments to place its bets.
Core Trading Logic
The script operates on a strictly scheduled basis. It looks for a specific "Trade Time" defined by the user (for example, 15:29). When that exact minute arrives, if there are no active positions open, the script automatically places two types of orders:
- Buy Stop Orders: Placed slightly above the current market price.
- Sell Stop Orders: Placed slightly below the current market price.
These are "pending" orders, meaning they will only activate if the price actually moves in that direction to hit the specific gap you have set.
Trade Management and Protection
Once a trade is activated (either a Buy or a Sell), the script takes over several management duties:
- Trailing Stop & Break-Even: To protect your profits, the script can "trail" the price. As the market moves in your favor, it automatically moves your stop-loss closer to the current price to lock in gains. It also includes a break-even feature that moves the stop-loss to the entry price once a certain profit level is reached.
- Order Cleanup: The script is designed to be organized. If it detects multiple pending orders but only one is active, it will automatically delete the "extra" pending orders to prevent unintended entries.
- Time-Based Expiration: The script has a designated "Finish Time." When this time is reached, it automatically clears out any remaining pending orders that were never triggered, ensuring your account isn't left with "hanging" orders overnight or during off-hours.
Money Management
The tool includes a sophisticated calculation system for trade sizing. Rather than always trading the same amount, it can be configured to calculate your lot size based on your actual account balance and a designated risk factor. This ensures that the amount of money risked on any single trade is proportional to your available funds.
Summary of Workflow
- Monitor: The script waits for the specific "Trade Time."
- Entry: At the target time, it places both Buy and Sell pending orders at a set distance from the price.
- Protection: If triggered, it actively manages the trade using trailing stops and profit protection.
- Cleanup: It constantly removes unnecessary pending orders and wipes all remaining orders once the "Finish Time" is reached.
//+------------------------------------------------------------------+
//| TimeBreakExpert_v1.1.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/"
#include <stdlib.mqh>
//#include <Tracert.mqh>
//---- input parameters
extern string ExpertName = "TimeBreakExpert_v2";
extern int Magic = 33333;
extern int Slippage = 6;
//extern bool Trace = false; // Trace Switch
extern string Main_Parameters = " Trade Volume & Trade Method";
extern double Lots = 0.2; // Lot size
extern bool StopTrade = false; // Stop of Trade switch
extern string Data = " Input Data ";
extern int TimeZone = 0; // Difference between server time and local time
extern string TimeTrade = "15:29"; // Local time of openning orders
extern string TimeFinish = "23:00"; // Local time of closing pending orders
extern double TakeProfit = 50; // Take Profit in pips
extern double TrailingStop = 15; // Trailing Stop in pips
extern double InitialStop = 20; // Initial Stop in pips
extern double BreakEven = 0; // Breakeven in pips
extern double PendOrdGap = 15; // Gap for Pending Orders from current price in pips
extern string MM_Parameters = " MoneyManagement by L.Williams ";
extern bool MM = false; // ÌÌ Switch
extern double MMRisk = 0.15; // Risk Factor
extern double LossMax = 1000; // Maximum Loss by 1 Lot
int cnt=0, ticket, mode=0, digit=0, numords;
double SellProfit=0,BuyProfit=0;
double BuyStop=0, SellStop=0, Lotsi=0;
bool BuyInTrade=false, SellInTrade=false;
datetime FinTime=0;
//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init()
{
//----
//----
return(0);
}
// ---- Money Management
double MoneyManagement ( bool flag, double Lots, double risk, double maxloss)
{
Lotsi=Lots;
if ( flag ) Lotsi=NormalizeDouble(Lots*AccountFreeMargin()*risk/maxloss,1);
if (Lotsi<0.1) Lotsi=0.1;
return(Lotsi);
}
// ---- Trailing Stops
void TrailStops()
{
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 ( BreakEven > 0 && Bid-OrderOpenPrice()>Point*BreakEven ) BuyStop = OrderOpenPrice();
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 ( BreakEven > 0 && OrderOpenPrice()-Ask>Point*BreakEven ) SellStop = OrderOpenPrice();
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 - PendOrdGap*Point;
if (InitialStop > 0) SellStop=SellPrice + InitialStop*Point; else SellStop=0;
if (TakeProfit > 0) SellProfit=SellPrice - TakeProfit*Point; else SellProfit=0;
//Print(" SellPrice=", SellPrice);
ticket = OrderSend( Symbol(),OP_SELLSTOP,Lotsi,
NormalizeDouble(SellPrice, Digits),
Slippage,
NormalizeDouble(SellStop , Digits),
NormalizeDouble(SellProfit , Digits),
ExpertName+" SELL",Magic,0,Red);
SellInTrade=false;
if(ticket<0)
{
Print("SELLSTOP: OrderSend failed with error #",GetLastError());
//
}
return(0);
}
// ---- Open Buy Orders
void BuyOrdOpen()
{
double BuyPrice =Ask + PendOrdGap*Point;
//Print(" BuyPrice=", BuyPrice);
if (InitialStop > 0) BuyStop = BuyPrice - InitialStop*Point; else BuyStop=0;
if (TakeProfit>0) BuyProfit=BuyPrice + TakeProfit*Point; else BuyProfit=0;
ticket = OrderSend(Symbol(),OP_BUYSTOP, Lotsi,
NormalizeDouble(BuyPrice, Digits),
Slippage,
NormalizeDouble(BuyStop , Digits),
NormalizeDouble(BuyProfit , Digits),
ExpertName+" BUY",Magic,0,Blue);
BuyInTrade=false;
if(ticket<0)
{
Print("BUYSTOP: OrderSend failed with error #",GetLastError());
//return(0);
}
return(0);
}
// ---- Delete Extra Orders
void ExtraOrdDel()
{
int total = OrdersTotal();
for (cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS);
mode=OrderType();
if ( OrderSymbol()==Symbol() && OrderMagicNumber()==Magic )
{
if (mode==OP_BUY && !BuyInTrade ) BuyInTrade =true;
if (mode==OP_SELL && !SellInTrade) SellInTrade=true;
if (mode > OP_SELL && (BuyInTrade || SellInTrade))
{
OrderDelete(OrderTicket());
}
}
}
}
// ---- Scan Trades
int ScanTrades()
{
int total = OrdersTotal();
numords = 0;
for(cnt=0; cnt<total; cnt++)
{
OrderSelect(cnt, SELECT_BY_POS);
if(OrderSymbol() == Symbol() && OrderType()>=OP_BUY && OrderMagicNumber() == Magic)
numords++;
}
return(numords);
}
// Closing of Pending Orders
void PendOrdDel()
{
int total=OrdersTotal();
for (int cnt=total-1;cnt>=0;cnt--)
{
OrderSelect(cnt, SELECT_BY_POS,MODE_TRADES);
if ( OrderSymbol()==Symbol() && OrderMagicNumber()==Magic )
{
int mode=OrderType();
bool result = false;
switch(mode)
{
case OP_BUYSTOP : result = OrderDelete( OrderTicket() );
case OP_SELLSTOP : result = OrderDelete( OrderTicket() );
if(!result)
{
Print("OrderDel failed with error #",GetLastError());
return(0);
}
//Print(" cnt=",cnt, " total=",total," MODE = ",mode," Ticket=",OrderTicket() );
}
}
}
//return;
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----
//----
return(0);
}
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
if(Bars < 1) {Print("Not enough bars for this strategy");return(0);}
if(AccountFreeMargin()<(1000*Lots)){
Print("We have no money. Free Margin = ", AccountFreeMargin());
return(0);}
//----
//if ( Trace ) SetTrace();
datetime OpenTime = StrToTime(TimeTrade) + TimeZone*3600;
if(!StopTrade && ScanTrades()<1 && (CurTime() >= OpenTime && CurTime() <= OpenTime+60))
{
Lotsi = MoneyManagement ( MM, Lots, MMRisk, LossMax);
BuyOrdOpen();
SellOrdOpen();
}
else
if (ScanTrades()>0)
{
ExtraOrdDel();
FinTime = StrToTime( TimeToStr(OrderOpenTime(), TIME_DATE) +" "+ TimeFinish) + TimeZone*3600;
//Print ( " FinTime(Close) =", TimeToStr(FinTime));
if (CurTime() >= FinTime && CurTime() <= FinTime + 60 ) PendOrdDel();
//Print("FinTime=",TimeToStr(FinTime,TIME_DATE|TIME_MINUTES));
if (TrailingStop>0 || BreakEven>0) TrailStops();
}
return(0);
}//int start
//+------------------------------------------------------------------+
Profitability Reports
Expected payoff
Average expected payoff across the available backtests for each symbol.
Comments