Say something meaningful or Silence!!
Similar Threads
I will code your pivot EAs for no charge 28 replies
I will code your scalping EAs for no charge 163 replies
Oanda MT4 - Indicators and EAs not showing 2 replies
EAs and indicators relating to moutaki... 22 replies
InterbankFX has loaded its MT4 platform with custom EAs, indicators and scripts 1 reply
- #74,481
- Jan 18, 2025 5:15am Jan 18, 2025 5:15am
- Joined Jun 2012 | Status: Trader , Analyst and Mentor | 5,884 Posts
Say something meaningful or Silence!!
- #74,482
- Jan 18, 2025 5:57am Jan 18, 2025 5:57am
- Joined Mar 2022 | Status: Trader | 6,558 Posts
Disliked{quote} I used the indicator for this week price action and it worked fine. Thank you again Can you please add the weekly open so one can track the weekly candle as it currently has daily open only and no other custom times. Is it also possible to have indicator id added so one can have 2 of the same indicator on one chart eg one on daily open and the other on weekly open. Thank you in advance for all your helpIgnored
Attached File(s)
Attached File(s)
.ex4/.ex5 files can't be fixed or modified / I'm not a coder!
- #74,483
- Edited 6:21am Jan 18, 2025 6:01am | Edited 6:21am
- Joined Mar 2022 | Status: Trader | 6,558 Posts
Disliked{quote} Just a thought if you're still having issues with this. Have you tried creating objects in a different order? Optionally, if not all code is available to you, adding indis or EA in a different order. All things being equal with Z orders (0 in this case) last created should be first in event queue for processing chart events. Regards.Ignored
It creates only one object across the whole chart (OBJ_BITMAPLABEL).
Adding indis in a sepcific order is only important when the indis plot buffers.
Otherwise MT4/5 don't know what priority the graphical object has, if the priority wasn't coded.
Read:
https://www.forexfactory.com/thread/...2#post15119342
.ex4/.ex5 files can't be fixed or modified / I'm not a coder!
- #74,484
- Jan 18, 2025 7:48am Jan 18, 2025 7:48am
- | Commercial User | Joined Aug 2019 | 2,245 Posts
DislikedHi Sirs, Kindly help with this Universal EA. I want to integrate an EMA filter into the existing MQL4 code without altering its original functionality. Just add EMA filter like 20 and 50. And if it crosses, it will close all open trades of the last bias and start a new trade of the new bias as long as there is an arrow. And it should only take signals based on the MA trend. Like if the MA crossing is bullish then it should only take buy arrows and vice versa for sell. Thank you in advance! ~Louise{file}
Ignored
Inserted Code
/*--------------------------------------------------------------------
Change-log: LUKE'S Universal EA_EMA_filter_v1.00
Date: 2025-01-18
By: MwlRCT
--------------------------------------------------------------------
- Integrated EMA filter for trend detection and trade filtering:
- Added input variables `EMA_Fast_Period` and `EMA_Slow_Period` for user-defined EMA periods.
- Calculated EMA values (`EMA_Fast` and `EMA_Slow`) in the `OnTick()` function using `iMA()`.
- Determined the current trend (`Current_Trend_Bullish`) based on the relationship between fast and slow EMAs.
- Modified the `GetSign()` function to generate trade signals only in the direction of the trend.
- Added logic in `OnTick()` to close trades when the trend reverses.
- Verified functionality through backtesting and forward testing on live charts.
-------------------------------------------------------------------- Download: LUKE'S Universal EA_EMA_filter_v1.00
Attached File(s)
Inserted Code
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx LUKE_PERRETT_ea.mq4 xxx//
/*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx specification xxx//
UNIVERSAL EA
This EA is to be based on buying /selling via buffers.
This is based on the calling of a custom signal indicator.
Here are the INPUTS below and I will give a description of how each INPUT works. Please see below.
Source code needs to be provided on completion of project.
EA INPUTS
Variable Value
TP Mode Basket/Individual
Lot Size 0.01
TP (IN $) 100
SL (IN $) 100
Trail TP (IN $) 250
Trail Step (IN $) 50
Break Even (IN $) 100
Custom Indicator Name X
Buy Buffer NO 0
Sell Buffer NO 1
Use Break Even True/False
Use Trailing Stop True/False
Use Close Out True/false
Close Out Trades Level 200
Close Out Style Break Even/Profit
Magic Number 777
TP Mode.
BASKET means for ALL trades to close out based on the TP/SL- OR Trail SL OR Break Even...
Basically its basket and everything closes based on the INPUTS. These figures are based on $, not pips
INDIVIDUAL means that ALL trades are closed out based on Individual circumstances of TP/SL/ Trail/ Breakeven etc etc.
These figures are based on $, not pips
LOT Size.
This is standard and needs for no explanation.
TP (IN $)
This means that all trades either in basket or individual will close out based on this $ amount. Simple
SL (IN $)
This means that all trades either in basket or individual will close out based on this $ amount. Simple
Trail TP (IN $)
This means that at this point of $ then the Trail of price will commence and will only be closed out be the Trail Step.
This is for basket or Individual.
Trail Step (IN $)
This means that when price in the Trail TP is reached. As price goes up or down, the Trail Step will close out trades based on this Step.
Example is.
Trail TP is set to $350,
Trail Step is set to $50,
Profit in trades is at $350,
Profit in trades falls back to $300.
Trades close out.
As profit rises then the step is rising with the profit at the same step level as the INPUT. SIMPLE.
This is seen as trailing the high water mark.
Break Even (IN $)
This means that either basket or individual will close out at this level.
Custom Indicator Name
This is where the custom indicator will go for this EA to call from the folder.
Buy Buffer
This is the number for the buffer for buying
Sell Buffer
This is the number for the buffer for selling
Use Break Even
This means the option to use break even feature or not
Use Trailing Stop
This means the option to use trailing stop feature or not
Use Close Out
This means the option to close out feature or not
Close Out Trades Level
This means for the trades to be closed out at this level based on the “Close Out Trades Style” INPUT.
I have added this feature because most brokers only allow a set amount of trades or pending orders.
So in this case the trades will close out ONLY 2 at a time based on the STYLE INPUT BELOW.
Obviously, trades will continue to be taken based on the entry criteria and in this case the trades will continue to close at this level as well.
In this case we will have trades closing at this level and trades also being entered based on the entry criteria
and trades also being closed out based on all the other INPUTS of TP/SL/Trailing/or Breakeven- based on basket or individual.
Close Out Trades Level
This is the level at which the 2 trades to close out will commence. This might be ranging from 10 to 500.
Depending on broker and system I use this for. Point to make is that 2 trades close out at the same time based on the “CLOSE OUT STYLE” INPUT
Close out Trades Style
This is the STYLE in which the 2 trades will close out when the “CLOSE OUT TRADES LEVEL” is reached.
Break Even. This means that the 2 trades to close should be the 2 trades closest to receiving a Break Even result. MUST BE A BUY AND SELL TRADE.
So a positive trade of $ 1.95 should be paired with the closest trade to receive a Break Even result.
This could be a negative trade of -$1.45. Either way the object is clear, the result to gain is that the 2 trades to close
give the closest to break even as possible.
Profit. This means the same as above INPUT yet the 2 trades to close out give the biggest profit. MUST BE A BUY AND SELL TRADE. Simple.
Best 2 trades at the time of closing to give biggest PROFIT.
Magic Number
This is obvious.
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
#property strict
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
enum ENUM_TP_MODE { Basket = 0, Individual = 1 };
enum ENUM_CLOSE_OUT_STYLE { BE = 0/*Break_Even*/, Profit = 1 };
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx external variables xxx//
input string _I_ = "___ EA INPUTS ___"; //
input ENUM_TP_MODE TP_Mode = Individual; // TP Mode
input double Lot_Size = 0.01; // Lot Size
input double TP_money = 100.0; // TP ( IN $ )
input double SL_money = 100.0; // SL ( IN $ )
input double Trail_TP = 250.0; // Trail TP ( IN $ )
input double Trail_Step = 50.0; // Trail Step ( IN $ )
input double Break_Even = 100.0; // Break Even ( IN $ )
input string Custom_Ind_Name = "X"; // Custom Indicator Name
input int Buy_Buffer_NO = 0; // Buy Buffer NO
input int Sell_Buffer_NO = 1; // Sell Buffer NO
input bool UseBreakEven = false; // Use Break Even
input bool UseTrailingStop = false; // Use Trailing Stop
input bool UseCloseOnOppSign = false; // Use Close On Opposite Signal
input bool UseCloseOut = false; // Use Close Out
input int CloseOutTradesLevel = 200; // Close Out Trades Level
input ENUM_CLOSE_OUT_STYLE CloseOutStyle = BE; // Close Out Style
input int Magic = 777; // Magic Number
input int EMA_Fast_Period = 20; // Fast EMA Period
input int EMA_Slow_Period = 50; // Slow EMA Period
/*input*/ int Slippage = 10; //
/*input*/ ENUM_TIMEFRAMES Tf = PERIOD_CURRENT; //
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx global variables xxx//
datetime
timePrev;
double
SL,TP,MaxProfitTrail,
TickSize,TickValue,Spread,StopLevel,MinLot,MaxLot,LotStep,Pnt;
int
order_type,T,nT,T_CloseOut,
nBO,nSO,nBS,nSS,nBL,nSL,nO,nS,nL,_nBO,_nSO,_nBS,_nSS,_nBL,_nSL,_nO,_nS,_nL,Slip;
bool
IsProfitBE, CloseContinue,
Ans,_Ans,Activate,FatalError,FreeMarginAlert,IsModify,IsTester,IsVisual;
int
tickets[];
double EMA_Fast, EMA_Slow; // Stores the current EMA values
bool Current_Trend_Bullish; // True if the trend is bullish (EMA_Fast > EMA_Slow), false otherwise
bool Previous_Trend_Bullish; // Stores the previous trend state for comparison
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx The initialization function of the expert xxx//
int OnInit()
{
Activate = false; FatalError = false;
//if( TimeCurrent() >= StringToTime( "2021.12.20 00:00" ) ) { Alert("The EA has expired !"); return( INIT_SUCCEEDED ); }
if( IsTesting() || IsOptimization() || IsVisualMode() ) IsTester = true; else IsTester = false;
if( IsOptimization() || ( IsTesting() && !IsVisualMode() ) ) IsVisual = false; else IsVisual = true;
Pnt = Point(); Slip = Slippage;
GetMarketInfo();
HistoryCheck();
timePrev = iTime( _Symbol, Tf, 0 );
if( IsTester || !GVC( "CloseContinue" ) )
{
CloseContinue = false;
T_CloseOut = -1;
MaxProfitTrail = 0.0;
IsProfitBE = false;
if( !IsTester )
{
GVS("MaxProfitTrail",MaxProfitTrail);
GVS("CloseContinue",(double)CloseContinue); GVS("T_CloseOut",(double)T_CloseOut); GVS("IsProfitBE",(double)IsProfitBE);
}
}
Activate = true;
return( INIT_SUCCEEDED );
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx The deinitialization function of the expert xxx//
void OnDeinit( const int reason )
{
Comment( "" );
if( !IsTester )
{
if( reason==0 || reason==1 )
{
GVD("MaxProfitTrail"); GVD("CloseContinue"); GVD("T_CloseOut"); GVD("IsProfitBE");
if( ObjectFind( 0, "TSL_lev" ) >= 0 ) { ObjectDelete( 0, "TSL_lev" ); ChartRedraw(); }
ArrayFree( tickets );
}
}
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx The main function of the expert xxx//
void OnTick()
{
if( !Activate || FatalError ) return;
if( !IsTester ) GetMarketInfo();
HistoryCheck(3,333);
// Calculate EMA values and determine the current trend
EMA_Fast = iMA(NULL, 0, EMA_Fast_Period, 0, MODE_EMA, PRICE_CLOSE, 0);
EMA_Slow = iMA(NULL, 0, EMA_Slow_Period, 0, MODE_EMA, PRICE_CLOSE, 0);
Previous_Trend_Bullish = Current_Trend_Bullish; // Store the previous trend
Current_Trend_Bullish = (EMA_Fast > EMA_Slow); // Update the current trend
// Close trades if the trend reverses
if (Current_Trend_Bullish != Previous_Trend_Bullish) // Trend has reversed
{
if (Current_Trend_Bullish) // New trend is bullish, close sell trades
{
ClosePos(OP_SELL);
}
else // New trend is bearish, close buy trades
{
ClosePos(OP_BUY);
}
}
//xxxxx
if( !IsTester ) CloseContinue = (bool)GVG( "CloseContinue" );
if( CloseContinue )
{
if( ClosePos() ) { CloseContinue = false; if( !IsTester ) { GVS( "CloseContinue", (double) CloseContinue ); GlobalVariablesFlush(); } }
else return;
}
//xxxxx
if( !IsTester ) T_CloseOut = (int)GVG( "T_CloseOut" );
if( T_CloseOut != -1 )
{
if( CloseByTicket( T_CloseOut ) ) { T_CloseOut = -1; if( !IsTester ) { GVS( "T_CloseOut", (double) T_CloseOut ); GlobalVariablesFlush(); } }
}
//xxxxx
Trade();
//xxxxx
getTickets();
_numbOrders();
//xxxxx
if( nO > 0 )
{
if( UseCloseOut )
CloseOut();
//xxxxx
if( TP_Mode == Individual )
{
if( SL_money > 0.0 || TP_money > 0.0 )
Check_SL_TP();
if( UseBreakEven )
Breakeven();
if( UseTrailingStop )
Trail();
}
//xxxxx
else
if( TP_Mode == Basket )
{
if( SL_money > 0.0 || TP_money > 0.0 )
{
Check_SL_TP_basket();
if( CloseContinue || nO <= 0 ) return;
}
if( UseBreakEven )
{
Breakeven_basket();
if( CloseContinue || nO <= 0 ) return;
}
if( UseTrailingStop )
{
Trail_basket();
if( CloseContinue || nO <= 0 ) return;
}
}
}
//xxxxx
else
if( nO <= 0 )
{
if( TP_Mode == Basket )
{
if( UseBreakEven && !IsTester ) IsProfitBE = (bool)GVG( "IsProfitBE" );
if( UseBreakEven && IsProfitBE )
{
IsProfitBE = false; if( !IsTester ) { GVS( "IsProfitBE", (double) IsProfitBE ); GlobalVariablesFlush(); }
}
if( UseTrailingStop && !IsTester ) MaxProfitTrail = GVG( "MaxProfitTrail" );
if( UseTrailingStop && MaxProfitTrail > 0.0 )
{
MaxProfitTrail = 0.0; if( !IsTester ) { GVS( "MaxProfitTrail", MaxProfitTrail ); GlobalVariablesFlush(); }
}
}
}
//xxxxx
if( IsVisual && TP_Mode == Basket && UseTrailingStop ) TSL_info();
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
void Trade()
{
int sign = GetSign();
if( sign == 1 && Current_Trend_Bullish ) order_type = OP_BUY; // Buy only in bullish trend
else if( sign == -1 && !Current_Trend_Bullish ) order_type = OP_SELL; // Sell only in bearish trend
else return; // No trade if trend and signal don't align
if( UseCloseOnOppSign )
{
getTickets(); _numbOrders();
if( ( sign == 1 && nSO > 0 ) || ( sign == -1 && nBO > 0 ) )
{
if( !ClosePos( sign == 1 ? OP_SELL : OP_BUY ) ) return;
}
}
if( MO( order_type, Lot_Size ) == -1 ) return;
timePrev = iTime( _Symbol, Tf, 0 );
if( TP_Mode == Individual && ( SL_money > 0.0 || TP_money > 0.0 ) )
{
if( tickValue() > 0.0 && tickSize() > 0.0 && point() > 0.0 )
{
double comm = fabs( commission( T ) );
if( SL_money > 0.0 ) SL = ( SL_money - comm ) / ( tickValue() * Lot_Size ) * ( tickSize() / point() ); else SL = 0.0;
if( TP_money > 0.0 ) TP = ( TP_money + comm ) / ( tickValue() * Lot_Size ) * ( tickSize() / point() ); else TP = 0.0;
ModifyByTicket( T );
}
}
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
int GetSign()
{
if( timePrev == iTime( _Symbol, Tf, 0 ) ) return( 0 );
double i_val = 0.0;
// Check for buy signal (only if trend is bullish)
if (Current_Trend_Bullish) {
i_val = iCustom(_Symbol, Tf, Custom_Ind_Name, Buy_Buffer_NO, 1);
if (i_val > 0.0 && i_val != EMPTY_VALUE) return(1);
}
// Check for sell signal (only if trend is bearish)
if (!Current_Trend_Bullish) {
i_val = iCustom(_Symbol, Tf, Custom_Ind_Name, Sell_Buffer_NO, 1);
if (i_val > 0.0 && i_val != EMPTY_VALUE) return(-1);
}
timePrev = iTime( _Symbol, Tf, 0 );
return(0); // No signal
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
double i_custom( int buf, int bar ) { return( iCustom( _Symbol, Tf, Custom_Ind_Name, buf, bar ) ); }
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
void CloseOut()
{
if( nO < CloseOutTradesLevel || nBO <= 0 || nSO <= 0 ) return;
int
i = 0, j = 0, t_buy = -1, t_sell = -1;
double
pf = 0.0, pf_buy = 0.0, pf_sell = 0.0;
if( CloseOutStyle == BE )
{
for( i = 0; i < nT; i++ )
{
if( ! OrderSelect( tickets[ i ], SELECT_BY_TICKET ) || OrderCloseTime() > 0 || OrderType() != OP_BUY ) continue;
pf_buy = ( OrderProfit() + OrderCommission() + OrderSwap() );
for( j = 0; j < nT; j++ )
{
if( ! OrderSelect( tickets[ j ], SELECT_BY_TICKET ) || OrderCloseTime() > 0 || OrderType() != OP_SELL ) continue;
pf_sell = ( OrderProfit() + OrderCommission() + OrderSwap() );
if( pf == 0 || fabs( pf_buy + pf_sell ) < pf )
{
pf = fabs( pf_buy + pf_sell );
t_buy = tickets[ i ];
t_sell = tickets[ j ];
}
}//for
}//for
}
else
if( CloseOutStyle == Profit )
{
for( i = 0; i < nT; i++ )
{
if( ! OrderSelect( tickets[ i ], SELECT_BY_TICKET ) || OrderCloseTime() > 0 || OrderType() > 1 ) continue;
pf = ( OrderProfit() + OrderCommission() + OrderSwap() );
if( OrderType() == OP_BUY && ( pf_buy == 0.0 || pf > pf_buy ) )
{
pf_buy = pf;
t_buy = tickets[ i ];
}
else
if( OrderType() == OP_SELL && ( pf_sell == 0.0 || pf > pf_sell ) )
{
pf_sell = pf;
t_sell = tickets[ i ];
}
}
}
if( t_buy != -1 && t_sell != -1 )
{
if( CloseByTicket( t_buy ) )
{
if( CloseByTicket( t_sell ) )
{
if( T_CloseOut != -1 ) T_CloseOut = -1;
}
else
T_CloseOut = t_sell;
if( !IsTester ) { GVS( "T_CloseOut", (double) T_CloseOut ); GlobalVariablesFlush(); }
getTickets();
_numbOrders();
}
}
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
void Check_SL_TP_basket()
{
double curr_result = GetCurrResultBasket();
if( ( SL_money != 0.0 && curr_result <= -fabs( SL_money ) ) || ( TP_money > 0.0 && curr_result >= TP_money ) )
{
CloseContinue = true; if( ClosePos() ) CloseContinue = false;
if( !IsTester ) { GVS( "CloseContinue", (double) CloseContinue ); GlobalVariablesFlush(); }
getTickets();
_numbOrders();
}
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
void Breakeven_basket()
{
if( !IsTester ) IsProfitBE = (bool)GVG( "IsProfitBE" );
if( !IsProfitBE && GetCurrResultBasket() >= Break_Even )
{
IsProfitBE = true;
if( !IsTester ) { GVS( "IsProfitBE", (double) IsProfitBE ); GlobalVariablesFlush(); }
}
else
if( IsProfitBE )
{
double money_lev_be = 0.0, lots_diff = CurrLotsDiffBuySell_basket();
if( lots_diff > 0.0 && tickValue() > 0.0 ) money_lev_be = tickValue() * lots_diff;
if( GetCurrResultBasket() <= money_lev_be )
{
CloseContinue = true; if( ClosePos() ) CloseContinue = false;
if( !CloseContinue )
{
IsProfitBE = false;
if( !IsTester ) { GVS( "IsProfitBE", (double) IsProfitBE ); GlobalVariablesFlush(); }
}
if( !IsTester ) { GVS( "CloseContinue", (double) CloseContinue ); GlobalVariablesFlush(); }
getTickets();
_numbOrders();
}
}
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
void Trail_basket()
{
if( !IsTester ) MaxProfitTrail = GVG( "MaxProfitTrail" );
double curr_result_basket = GetCurrResultBasket();
if( MaxProfitTrail <= 0.0 && curr_result_basket >= Trail_TP )
{
MaxProfitTrail = curr_result_basket;
if( !IsTester ) { GVS( "MaxProfitTrail", MaxProfitTrail ); GlobalVariablesFlush(); }
}
else
if( MaxProfitTrail > 0.0 && curr_result_basket > MaxProfitTrail )
{
MaxProfitTrail = curr_result_basket;
if( !IsTester ) { GVS( "MaxProfitTrail", MaxProfitTrail ); GlobalVariablesFlush(); }
}
else
if( MaxProfitTrail > 0.0 && curr_result_basket <= MaxProfitTrail - Trail_Step )
{
CloseContinue = true; if( ClosePos() ) CloseContinue = false;
if( !CloseContinue )
{
MaxProfitTrail = 0.0;
if( !IsTester ) { GVS( "MaxProfitTrail", MaxProfitTrail ); GlobalVariablesFlush(); }
}
if( !IsTester ) { GVS( "CloseContinue", (double) CloseContinue ); GlobalVariablesFlush(); }
getTickets();
_numbOrders();
}
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
void Check_SL_TP()
{
int
i = 0;
color
c = clrNONE;
double
sl = 0.0, tp = 0.0, sl_lev = 0.0, tp_lev = 0.0, comm_and_swap = 0.0, comm_swap_pnt = 0.0;
for( i = 0; i < nT; i++ )
{
if( !OrderSelect( tickets[ i ], SELECT_BY_TICKET ) || OrderCloseTime() > 0 || OrderType() > 1 ) continue;
comm_and_swap = ( OrderCommission() + OrderSwap() );
comm_swap_pnt = 0.0;
if( comm_and_swap < 0.0 && tickValue() > 0.0 && tickSize() > 0.0 && point() > 0.0 )
{
comm_swap_pnt = fabs( comm_and_swap ) / ( tickValue() * OrderLots() ) * ( tickSize() / point() );
comm_swap_pnt = MathCeil( comm_swap_pnt );
}
if( SL_money > 0.0 ) sl = SL_money / ( tickValue() * OrderLots() ) * ( tickSize() / point() ) - comm_swap_pnt; else sl = 0.0;
if( TP_money > 0.0 ) tp = TP_money / ( tickValue() * OrderLots() ) * ( tickSize() / point() ) + comm_swap_pnt; else tp = 0.0;
if( OrderType() == OP_BUY )
{
if( OrderStopLoss() > 0.0 && OrderStopLoss() >= OrderOpenPrice() )
sl_lev = OrderStopLoss();
else
sl_lev = sl > 0.0 ? OrderOpenPrice() - sl*Pnt : 0.0;
tp_lev = tp > 0.0 ? OrderOpenPrice() + tp*Pnt : 0.0;
if( ( tp_lev > 0.0 && tp_lev - Bid < _stopLevel() ) || ( sl_lev > 0.0 && Bid - sl_lev < _stopLevel() ) ) continue;
c = clrBlue;
}
else
if( OrderType() == OP_SELL )
{
if( OrderStopLoss() > 0.0 && OrderStopLoss() <= OrderOpenPrice() )
sl_lev = OrderStopLoss();
else
sl_lev = sl > 0.0 ? OrderOpenPrice() + sl*Pnt : 0.0;
tp_lev = tp > 0.0 ? OrderOpenPrice() - tp*Pnt : 0.0;
if( ( tp_lev > 0.0 && Ask - tp_lev < _stopLevel() ) || ( sl_lev > 0.0 && sl_lev - Ask < _stopLevel() ) ) continue;
c = clrRed;
}
if( fabs( sl_lev - OrderStopLoss() ) >= Pnt || fabs( tp_lev - OrderTakeProfit() ) >= Pnt )
{
F_ord_mod( sl_lev, tp_lev, -1.0, c );
}
}
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
int getTickets()
{
int
j=0,n=0,pos=0;
ArrayResize(tickets,1,10); ArrayInitialize(tickets,-1);
for(pos=OrdersTotal()-1;pos>=0;pos--)
{
for(j=0;j<10;j++){if(OrderSelect(pos,SELECT_BY_POS))break;/*=>*/if(j<9)Sleep(100);}/*for =>*/if(j==10)continue;
if(OrderSymbol()!=_Symbol||OrderMagicNumber()!=Magic)continue;
ArrayResize(tickets,n+1,10); tickets[n]=OrderTicket(); n++;
}//for
nT=n;
return(n);
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
void _numbOrders(int i=0){nBO=0;nSO=0;nBS=0;nSS=0;nBL=0;nSL=0;nO=0;nS=0;nL=0;
int
j=0,pos=0;
nT=getTickets();
for(pos=0;pos<nT;pos++) {
for(j=0;j<10;j++){if(OrderSelect(tickets[pos],SELECT_BY_TICKET))break;/*=>*/if(j<9)Sleep(100);}/*for =>*/if(j==10)continue;
if(OrderCloseTime()!=0)continue;
switch(OrderType()){case 0: nBO++; break; case 1: nSO++; break;
case 2: nBL++; break; case 3: nSL++; break;
case 4: nBS++; break; case 5: nSS++; break;}/*switch*/}//for
nO=nBO+nSO; nS=nBS+nSS; nL=nBL+nSL;
if(i==0) return; else
if(i==1) { _nBO=nBO; _nSO=nSO; _nBS=nBS; _nSS=nSS; _nBL=nBL; _nSL=nSL; _nO=nO; _nS=nS; _nL=nL; } }
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
double GetCurrResultBasket()
{
double curr_profit_basket = 0.0;
for( int i = 0; i < nT; i++ )
{
if( ! OrderSelect( tickets[ i ], SELECT_BY_TICKET ) || OrderCloseTime() > 0 || OrderType() > 1 ) continue;
curr_profit_basket += ( OrderProfit() + OrderCommission() + OrderSwap() );
}
return( curr_profit_basket );
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
double CurrLotsDiffBuySell_basket()
{
double curr_lots_buy = 0.0, curr_lots_sell = 0.0;
for( int i = 0; i < nT; i++ )
{
if( ! OrderSelect( tickets[ i ], SELECT_BY_TICKET ) || OrderCloseTime() > 0 ) continue;
if( OrderType() == OP_BUY ) curr_lots_buy += OrderLots();
else
if( OrderType() == OP_SELL ) curr_lots_sell += OrderLots();
}
return( fabs( curr_lots_buy - curr_lots_sell ) );
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
double op(int t=-1){if(t!=-1&&!OrderSelect(t,SELECT_BY_TICKET))return(0.0);else return(OrderOpenPrice());}
double cp(int t=-1){if(t!=-1&&!OrderSelect(t,SELECT_BY_TICKET))return(0.0);else return(OrderClosePrice());}
double lot(int t=-1){if(t!=-1&&!OrderSelect(t,SELECT_BY_TICKET))return(0.0);else return(OrderLots());}
double sl(int t=-1){if(t!=-1&&!OrderSelect(t,SELECT_BY_TICKET))return(0.0);else return(OrderStopLoss());}
double tp(int t=-1){if(t!=-1&&!OrderSelect(t,SELECT_BY_TICKET))return(0.0);else return(OrderTakeProfit());}
double profit(int t=-1){if(t!=-1&&!OrderSelect(t,SELECT_BY_TICKET))return(0.0);else return(OrderProfit());}
double swap(int t=-1){if(t!=-1&&!OrderSelect(t,SELECT_BY_TICKET))return(0.0);else return(OrderSwap());}
double commission(int t=-1){if(t!=-1&&!OrderSelect(t,SELECT_BY_TICKET))return(0.0);else return(OrderCommission());}
double result(int t=-1){if(t!=-1&&!OrderSelect(t,SELECT_BY_TICKET))return(0.0);else return(OrderProfit()+OrderSwap()+OrderCommission());}
int type(int t=-1){if(t!=-1&&!OrderSelect(t,SELECT_BY_TICKET))return(0.0);else return(OrderType());}
int id(int t=-1){if(t!=-1&&!OrderSelect(t,SELECT_BY_TICKET))return(0.0);else return(OrderMagicNumber());}
int ot(int t=-1){if(t!=-1&&!OrderSelect(t,SELECT_BY_TICKET))return(0.0);else return((int)OrderOpenTime());}
int ct(int t=-1){if(t!=-1&&!OrderSelect(t,SELECT_BY_TICKET))return(0.0);else return((int)OrderCloseTime());}
string comm(int t=-1){if(t!=-1&&!OrderSelect(t,SELECT_BY_TICKET))return("");else return(OrderComment());}
string symb(int t=-1){if(t!=-1&&!OrderSelect(t,SELECT_BY_TICKET))return("");else return(OrderSymbol());}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
bool Trail(int type_ord=-1){
//xxxxx
bool _ans=true;
for(int pos=0;pos<nT;pos++){
if(!OrderSelect(tickets[ pos ],SELECT_BY_TICKET)||OrderCloseTime()>0||OrderType()>1)continue;
if(type_ord>-1&&type_ord!=OrderType())continue;
if(!trailByTicket()){if(_ans)_ans=false;}
}//for
//xxxxx
return(_ans);
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
bool trailByTicket(int t=-1){
if(t!=-1&&!OrderSelect(t,SELECT_BY_TICKET))return(false);
//xxxxx
double sl_lev=0.0, profit=0.0, trail_step_pnt=0.0; color c=clrNONE;
profit = ( profit() + commission() + swap() );
if( profit < Trail_TP ) return( true );
if( tickValue() > 0.0 && tickSize() > 0.0 && point() > 0.0 )
{
trail_step_pnt = Trail_Step / ( tickValue() * OrderLots() ) * ( tickSize() / point() );
trail_step_pnt = MathCeil( trail_step_pnt );
}
else
return( false );
//xxxxx
if(OrderType()==OP_BUY){
if(sl()!=0.0&&ND(Bid-sl())<=trail_step_pnt*Pnt)return(true);
sl_lev=Bid-trail_step_pnt*Pnt;
if(ND(Bid-sl_lev)<StopLevel)return(false);
c=clrBlue;}
//xxxxx
else
if(OrderType()==OP_SELL){
if(sl()!=0.0&&ND(sl()-Ask)<=trail_step_pnt*Pnt)return(true);
sl_lev=Ask+trail_step_pnt*Pnt;
if(ND(sl_lev-Ask)<StopLevel)return(false);
c=clrRed;}
//xxxxx
return( F_ord_mod(sl_lev,-1.0,-1.0,c) );
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
bool Breakeven(int type_ord=-1){
//xxxxx
bool _ans=true;
for(int pos=0;pos<nT;pos++){
if(!OrderSelect(tickets[ pos ],SELECT_BY_TICKET)||OrderCloseTime()>0||OrderType()>1)continue;
if(type_ord>-1&&type_ord!=OrderType())continue;
if(!beByTicket()){if(_ans)_ans=false;}
}//for
//xxxxx
return(_ans);
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
bool beByTicket(int t=-1){
if(t!=-1&&!OrderSelect(t,SELECT_BY_TICKET))return(false);
//xxxxx
double sl_lev=0.0, comm_and_swap=0.0, comm_swap_pnt=0.0, profit=0.0; color c=clrNONE;
comm_and_swap = ( commission() + swap() );
profit = ( profit() + comm_and_swap );
if( profit < Break_Even ) return( true );
if( comm_and_swap < 0.0 && tickValue() > 0.0 && tickSize() > 0.0 && point() > 0.0 )
{
comm_swap_pnt = fabs( comm_and_swap ) / ( tickValue() * OrderLots() ) * ( tickSize() / point() );
comm_swap_pnt = MathCeil( comm_swap_pnt );
}
//xxxxx
if(OrderType()==OP_BUY){
sl_lev=op()+comm_swap_pnt*Pnt;
if(sl()!=0.0&&ND(sl()-sl_lev)>=0.0)return(true);
if(ND(Bid-sl_lev)<StopLevel)return(false);
c=clrBlue;}
//xxxxx
else
if(OrderType()==OP_SELL){
sl_lev=op()-comm_swap_pnt*Pnt;
if(sl()!=0.0&&ND(sl_lev-sl())>=0.0)return(true);
if(ND(sl_lev-Ask)<StopLevel)return(false);
c=clrRed;}
//xxxxx
return( F_ord_mod(sl_lev,-1.0,-1.0,c) );
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
bool F_ord_mod(double sl_lev=-1.0,double tp_lev=-1.0,double op_lev=-1.0,color c=clrNONE){
if(sl_lev==-1.0)sl_lev=sl(); if(tp_lev==-1.0)tp_lev=tp(); if(op_lev==-1.0)op_lev=op();
if(ND(sl_lev-sl())==0.0&&ND(tp_lev-tp())==0.0&&ND(op_lev-op())==0.0)return(true);
//xxxxx
int i=0; bool ans=false;
while(!ans&&i<5){
ans=OrderModify(OrderTicket(),NT(op_lev),NT(sl_lev),NT(tp_lev),NULL,c);
if(!ans){if(!Errors(GetLastError()))break;}
i++;}//while
//xxxxx
return(ans);
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
int MO(int type, double lot, string comment="") { // market order
double price; color c; int i=0; T=-1; RefreshRates();
if(type==OP_BUY) { c=clrBlue; price=Ask; } else if(type==OP_SELL) { c=clrRed; price=Bid; } else return(T);
if(AccountFreeMarginCheck(Symbol(),type,NL(lot))<=0.0 || GetLastError()==134) {
if(!FreeMarginAlert) { Alert("Not enough money to send the order. Free Margin = ", DoubleToStr(AccountFreeMargin(),2));
FreeMarginAlert=true; } return(T); } FreeMarginAlert=false;
while(T<0 && i<5) {
T=OrderSend(Symbol(),type,NL(lot),NT(price),2*(int)MarketInfo(Symbol(),MODE_SPREAD),NULL,NULL,comment,Magic,NULL,c);
if(T<0) { if(!Errors(GetLastError())) return(T); } i++; } /*while*/ return(T); }
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
bool ModifyByTicket(int ticket,int slType=0,int tpType=0) {
if(SL==0.0 && TP==0.0) return(true);
if(!OrderSelect(ticket,SELECT_BY_TICKET)) return(false);
double sl=0.0, tp=0.0, _sl=OrderStopLoss(), _tp=OrderTakeProfit(), op=OrderOpenPrice();
int i=0;
color c=clrNONE;
RefreshRates();
if(OrderType()==OP_BUY) {
if(TP>0.0) { if(tpType==0)tp=op+fmax(TP*Pnt,StopLevel);else if(tpType==1)tp=TP; if(ND(tp-Bid)<StopLevel) tp=Bid+1.5*StopLevel; }
if(SL>0.0) { if(slType==0)sl=op-fmax(SL*Pnt,StopLevel);else if(slType==1)sl=SL; if(ND(Bid-sl)<StopLevel) sl=Bid-1.5*StopLevel; }
c=clrBlue;
}
else if(OrderType()==OP_SELL) {
if(TP>0.0) { if(tpType==0)tp=op-fmax(TP*Pnt,StopLevel);else if(tpType==1)tp=TP; if(ND(Ask-tp)<StopLevel) tp=Ask-1.5*StopLevel; }
if(SL>0.0) { if(slType==0)sl=op+fmax(SL*Pnt,StopLevel);else if(slType==1)sl=SL; if(ND(sl-Ask)<StopLevel) sl=Ask+1.5*StopLevel; }
c=clrRed;
}
if(ND(sl-_sl)==0.0 && ND(tp-_tp)==0.0) return(true);
i=0; Ans=false;
while(!Ans && i<5) {
Ans=OrderModify(ticket,NT(op),NT(sl),NT(tp),0,c);
if(!Ans) { if(!Errors(GetLastError())) break; } i++; } /*while*/ return(Ans); }
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
bool ClosePos(int type=-1) { double price; int i; color c;
_Ans=true;
for(int pos=OrdersTotal()-1; pos>=0; pos--) {
if(!OrderSelect(pos,SELECT_BY_POS,MODE_TRADES) || OrderSymbol()!=Symbol() || OrderMagicNumber()!=Magic) continue;
if(OrderType()>1 || (type>=0 && type!=OrderType())) continue;
RefreshRates();
i=0; Ans=false;
while(!Ans && i<5) {
if(OrderType()==OP_BUY) { price=Bid; c=clrBlue; } else { price=Ask; c=clrRed; }
Ans=OrderClose(OrderTicket(),OrderLots(),NT(price),2*(int)MarketInfo(Symbol(),MODE_SPREAD),c);
if(!Ans) { if(!Errors(GetLastError())) break; } i++; } /*while*/ if(!Ans) _Ans=false; } /*for*/ return(_Ans); }
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
bool CloseByTicket(int ticket, double lot=0.0) {
if(!OrderSelect(ticket,SELECT_BY_TICKET))return(false);
if(OrderCloseTime()>0)return(true);
if(lot<=0.0) lot=OrderLots();
double price; int i; color c;
RefreshRates();
i=0; Ans=false;
while(!Ans && i<5) {
if(OrderType()==OP_BUY) { price=Bid; c=clrBlue; } else { price=Ask; c=clrRed; }
Ans=OrderClose(OrderTicket(),NL(lot),NT(price),2*(int)MarketInfo(Symbol(),MODE_SPREAD),c);
if(!Ans) { if(!Errors(GetLastError())) break; } i++; } /*while*/ return(Ans); }
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
bool HistoryCheck(int n=10,int sleep=1000) {
int i=0;
while(i<n) {
if(TimeCurrent()-iTime(NULL,Tf,0)<PeriodSeconds(Tf))
{
break;
}
Comment("Loading history of quotes ...");
Sleep(sleep);
i++;
}//while
if(i==n) { /*Comment("Update failed. Go to the next attempt.");*/Comment(""); return(false); }
Comment(""); return(true); }
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
void GetMarketInfo() {
TickSize=tickSize(); TickValue=tickValue(); Spread=_spread(); StopLevel=_stopLevel(); MinLot=minLot(); MaxLot=maxLot(); LotStep=lotStep(); }
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
double tickSize(string symb=""){if(symb=="")symb=Symbol();return(MarketInfo(symb,MODE_TICKSIZE));}
double tickValue(string symb=""){if(symb=="")symb=Symbol();return(MarketInfo(symb,MODE_TICKVALUE));}
double spread(string symb=""){if(symb=="")symb=Symbol();return(MarketInfo(symb,MODE_SPREAD));}
double _spread(string symb=""){if(symb=="")symb=Symbol();return(MarketInfo(symb,MODE_SPREAD)*point());}
double stopLevel(string symb=""){if(symb=="")symb=Symbol();return(MarketInfo(symb,MODE_STOPLEVEL));}
double _stopLevel(string symb=""){if(symb=="")symb=Symbol();return(MarketInfo(symb,MODE_STOPLEVEL)*point());}
double freezeLevel(string symb=""){if(symb=="")symb=Symbol();return(MarketInfo(symb,MODE_FREEZELEVEL));}
double _freezeLevel(string symb=""){if(symb=="")symb=Symbol();return(MarketInfo(symb,MODE_FREEZELEVEL)*point());}
double minLot(string symb=""){if(symb=="")symb=Symbol();return(MarketInfo(symb,MODE_MINLOT));}
double maxLot(string symb=""){if(symb=="")symb=Symbol();return(MarketInfo(symb,MODE_MAXLOT));}
double lotStep(string symb=""){if(symb=="")symb=Symbol();return(MarketInfo(symb,MODE_LOTSTEP));}
double bid(string symb=""){if(symb=="")symb=Symbol();return(MarketInfo(symb,MODE_BID));}
double ask(string symb=""){if(symb=="")symb=Symbol();return(MarketInfo(symb,MODE_ASK));}
double point(string symb=""){if(symb=="")symb=Symbol();return(MarketInfo(symb,MODE_POINT));}
int digits(string symb=""){if(symb=="")symb=Symbol();return((int)MarketInfo(symb,MODE_DIGITS));}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
double NL(double L) {
return( MathRound(MathMin(MathMax(L, MinLot), MaxLot)/LotStep)*LotStep ); }
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
double ND(double A, int digits=0) {
if(digits<=0) digits=Digits();
return( NormalizeDouble(A, digits) ); }
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
double NT(double A, int direction=0) { double _A=MathRound(A/TickSize)*TickSize;
if(direction==1) { if(ND(A-_A)>0.0) _A+=TickSize; } else if(direction==-1) { if(ND(A-_A)<0.0) _A-=TickSize; }
return(_A); }
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
datetime GVS(string name,double value){return(GlobalVariableSet(name+Name(),value));}
datetime GVZ(string name){return(GlobalVariableSet(name+Name(),0.0));}
double GVG(string name){return(GlobalVariableGet(name+Name()));}
bool GVD(string name){return((bool)GlobalVariableDel(name+Name()));}
bool GVC(string name){return( GlobalVariableCheck(name+Name()));}
string Name(){if(IsTester)return("_"+IntegerToString(Magic)+"_"+Symbol()+"_"+"Tester");else return("_"+IntegerToString(Magic)+"_"+Symbol());}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
bool Errors(int Error) {
if(Error==0) return(false); // No error
switch(Error) {
// Crucial errors:
case 4: // Trade server is busy
Sleep(3000); RefreshRates();
return(true); // Avoidable error
case 129: // Wrong price
case 135: // Price changed
RefreshRates(); // Refresh data
return(true); // Avoidable error
case 136: // No prices. Waiting for a new tick.
while(!RefreshRates()) Sleep(1);
return(true); // Avoidable error
case 137: // Broker is busy
Sleep(3000); RefreshRates();
return(true); // Avoidable error
case 146: // Trading subsystem is busy
Sleep(500); RefreshRates();
return(true); // Avoidable error
// Fatal error:
case 2 : // Generic error
case 5 : // The old version of the client terminal
case 64: // Account blocked
case 133: // Trading is prohibited
Alert("A fatal error - expert stopped!"); FatalError=true; return(false); // Fatal error
default: // Other variants
return(false); } /*switch*/ }
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
void TSL_info()
{
if( !IsTester ) MaxProfitTrail = GVG( "MaxProfitTrail" );
if( MaxProfitTrail > 0.0 )
{
drawLbl( "TSL_lev", "TSL LEVEL : " + DoubleToString( MaxProfitTrail - Trail_Step, 2 ) + " " + AccountCurrency(),
CORNER_LEFT_UPPER, 20, 20, 12, "Tahoma", clrGold );
}
else
if( MaxProfitTrail <= 0.0 )
{
if( ObjectFind( 0, "TSL_lev" ) >= 0 ) ObjectDelete( 0, "TSL_lev" );
}
ChartRedraw();
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
void drawLbl( string name, string s, ENUM_BASE_CORNER corner, int DX, int DY, int FSize, string Font, color c, bool bg=false )
{
if( ObjectFind(0,name) < 0 ) { ObjectCreate( 0, name, OBJ_LABEL, 0, 0, 0 ); }
ObjectSetInteger( 0, name, OBJPROP_CORNER, corner );
ObjectSetInteger( 0, name, OBJPROP_XDISTANCE, DX );
ObjectSetInteger( 0, name, OBJPROP_YDISTANCE, DY );
ObjectSetInteger( 0, name, OBJPROP_BACK, bg );
ObjectSetString ( 0, name, OBJPROP_TEXT, s );
ObjectSetString ( 0, name, OBJPROP_FONT, Font );
ObjectSetInteger( 0, name, OBJPROP_FONTSIZE, FSize );
ObjectSetInteger( 0, name, OBJPROP_COLOR, c );
ObjectSetInteger( 0, name, OBJPROP_SELECTABLE, false );
ObjectSetInteger( 0, name, OBJPROP_HIDDEN, true );
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
/*--------------------------------------------------------------------
Change-log: LUKE'S Universal EA_EMA_filter_v1.00
Date: 2025-01-18
By: MwlRCT
--------------------------------------------------------------------
- Integrated EMA filter for trend detection and trade filtering:
- Added input variables `EMA_Fast_Period` and `EMA_Slow_Period` for user-defined EMA periods.
- Calculated EMA values (`EMA_Fast` and `EMA_Slow`) in the `OnTick()` function using `iMA()`.
- Determined the current trend (`Current_Trend_Bullish`) based on the relationship between fast and slow EMAs.
- Modified the `GetSign()` function to generate trade signals only in the direction of the trend.
- Added logic in `OnTick()` to close trades when the trend reverses.
- Verified functionality through backtesting and forward testing on live charts.
--------------------------------------------------------------------
- Enhanced trade execution logic:
- Updated the `Trade()` function to ensure trades are executed only when they align with the detected trend.
- Added checks to prevent trades from being executed against the trend.
- Verified trade execution logic through extensive testing in trending and ranging markets.
--------------------------------------------------------------------
- Improved debugging and logging:
- Added `Print()` statements to log key variables (e.g., EMA values, trend states, trade signals) for debugging purposes.
- Verified logging functionality during backtests and live testing.
--------------------------------------------------------------------
- Optimized performance:
- Reduced redundant calculations in the `OnTick()` function by storing EMA values and trend states in global variables.
- Verified performance improvements through testing on multiple currency pairs and timeframes.
--------------------------------------------------------------------
- Updated documentation:
- Added comments to explain the purpose of new variables and functions.
- Documented the changes in the debugging report for future reference.
- Verified documentation accuracy through peer review.
--------------------------------------------------------------------*/
[b][/b] 2
- #74,485
- Jan 18, 2025 8:10am Jan 18, 2025 8:10am
Disliked{quote} This one is open source, and a very simple one, too. So, you can add your extra condtions. {file} There are only these two if's: {image} and you can add your conditions to them. Example: // Up Candle if (low > high[i+2] && close > open && close[i+1] > open[i+1] && close[i+2] > open[i+2] && close[i+3] > open[i+3]) { _up_BodyHigh = low; _up_BodyLow = high[i+2]; } // Down Candle if (high < low[i+2] && close < open && close[i+1] < open[i+1] && close[i+2] < open[i+2] && close[i+3] < open[i+3]) { _dn_BodyHigh = low[i+2];...Ignored
- #74,486
- Jan 18, 2025 8:21am Jan 18, 2025 8:21am
Disliked{quote} {quote} maybe you could use this to get the anchor time and price for obj_trend? https://docs.mql4.com/chart_operatio...txytotimeprice and: Long height = chartgetinteger(0,chart_height_in_pixels,0); long width = chartgetinteger(0,chart_width_in_pixels,0); so, one line goes from x=0 and y=0 to x=chart_width_in_pixels and y=chart_height_in_pixels. The other line goes from x=0 and y=chart_height_in_pixels to x=chart_width_in_pixels and y=0. {file} this is independent of the chart graph, itself - only reads the window size in...Ignored
Thnx in advance
Attached File(s)
1
Dear Mr. Jnevins,
May I make a second request to convert another MT4 EA to MT5.
The EA uses two indicators that probably also need to be converted.
If I ask too much now, I hereby apologize.
With Regards,
Herman
May I make a second request to convert another MT4 EA to MT5.
The EA uses two indicators that probably also need to be converted.
If I ask too much now, I hereby apologize.
With Regards,
Herman
Attached File(s)
- #74,488
- Jan 18, 2025 9:31am Jan 18, 2025 9:31am
Disliked{quote} /*-------------------------------------------------------------------- Change-log: LUKE'S Universal EA_EMA_filter_v1.00 Date: 2025-01-18 By: MwlRCT -------------------------------------------------------------------- - Integrated EMA filter for trend detection and trade filtering: - Added input variables `EMA_Fast_Period` and `EMA_Slow_Period` for user-defined EMA periods. - Calculated EMA values (`EMA_Fast` and `EMA_Slow`) in the `OnTick()` function using `iMA()`. - Determined the current trend (`Current_Trend_Bullish`) based on the relationship...Ignored
It worked! I can't thank you enough. Much appreciated.
~Kim Louise
My advice is to invest in tennis balls. They have a high rate of return.
1
- #74,489
- Jan 18, 2025 9:54am Jan 18, 2025 9:54am
Disliked{quote} /*-------------------------------------------------------------------- change-log: Luke's universal ea_ema_filter_v1.00 date: 2025-01-18 by: Mwlrct -------------------------------------------------------------------- - integrated ema filter for trend detection and trade filtering: - added input variables `ema_fast_period` and `ema_slow_period` for user-defined ema periods. - calculated ema values (`ema_fast` and `ema_slow`) in the `ontick()` function using `ima()`. - determined the current trend (`current_trend_bullish`) based on the relationship...Ignored
- #74,490
- Jan 18, 2025 10:30am Jan 18, 2025 10:30am
- | Commercial User | Joined Aug 2019 | 2,245 Posts
Disliked{quote} how are you sir hope all is fine, if you please could you add another 2 lines vertical and horizontal like picture attached , just when you have time, sorry i ask you alot sir. Thnx in advance {image} {file}Ignored
Download:
Attached File(s)
1
- #74,491
- Jan 18, 2025 10:45am Jan 18, 2025 10:45am
- | Commercial User | Joined Aug 2019 | 2,245 Posts
Disliked{quote} how are you sir hope all is fine, if you please could you add another 2 lines vertical and horizontal like picture attached , just when you have time, sorry i ask you alot sir. Thnx in advance {image} {file}Ignored
- #74,492
- Jan 18, 2025 10:50am Jan 18, 2025 10:50am
- Joined Mar 2022 | Status: Trader | 6,558 Posts
Disliked{quote} how are you sir hope all is fine, if you please could you add another 2 lines vertical and horizontal like picture attached , just when you have time, sorry i ask you alot sir. Thnx in advance {image} {file}Ignored
Attached File(s)
.ex4/.ex5 files can't be fixed or modified / I'm not a coder!
1
- #74,495
- Jan 18, 2025 11:13am Jan 18, 2025 11:13am
Hi all.
Trying to make a strategy in pinescript to backtest over a few years. It's a swing low strategy that is triggered by the 4th candle breaking the high of the 3rd candle. The stop is the low of the 3rd candle (trigger candle)
I've tried chatgpt and although it's profitable, looking in on each trade it seems as though it cherry picks the trades and doesn't enter valid positions on the chart. Also the stop loss isn't triggered on valid triggers. Here is the code
// Strategy: Swing Low Detection with Entry, Stop, and Take Profit
//@version=5
strategy("Swing Low Detection", overlay=true)
// Detect Swing Lows Using a 3-Candle Formation
swingLow = low[1] < low[0] and low[1] < low[2] ? low[1] : na
// Plot Swing Lows
plot(swingLow, title="Swing Low", color=color.green, style=plot.style_cross, linewidth=2)
// Mark Swing Lows and the 3rd Candle Details
if (not na(swingLow))
label.new(bar_index[1], swingLow, "Swing Low", color=color.green, style=label.style_label_down, textcolor=color.white)
label.new(bar_index[1], high[1], "Entry (High): " + str.tostring(high[1]), color=color.blue, style=label.style_label_up, textcolor=color.white)
label.new(bar_index[1], low[1], "Stop (Low): " + str.tostring(low[1]), color=color.red, style=label.style_label_down, textcolor=color.white)
// Entry, Stop, and Take Profit Logic for 4th Candle
if (not na(swingLow))
entryPrice = high[1] + syminfo.mintick // Entry is slightly above the high of the 3rd candle
stopPrice = low[1] // Stop is exactly the low of the 3rd candle
risk = entryPrice - stopPrice // Risk per trade
takeProfit = entryPrice + (risk * 2) // Take profit at 2R
// Trigger orders on the 4th candle only if the high is significantly broken
if high[0] > entryPrice and close > entryPrice
strategy.entry("Long", strategy.long)
strategy.exit("Take Profit", from_entry="Long", limit=takeProfit, stop=stopPrice)
// Mark the triggered entry, stop, and take profit
label.new(bar_index, entryPrice, "Triggered Entry\nPrice: " + str.tostring(entryPrice), color=color.green, style=label.style_label_up, textcolor=color.white)
label.new(bar_index, stopPrice, "Triggered Stop\nPrice: " + str.tostring(stopPrice), color=color.red, style=label.style_label_down, textcolor=color.white)
label.new(bar_index, takeProfit, "Take Profit\nPrice: " + str.tostring(takeProfit), color=color.blue, style=label.style_label_up, textcolor=color.white)
Here is a screenshot of some of the trades taken :
https://files.oaiusercontent.com/fil...waBtVO4Dstk%3D
Trying to make a strategy in pinescript to backtest over a few years. It's a swing low strategy that is triggered by the 4th candle breaking the high of the 3rd candle. The stop is the low of the 3rd candle (trigger candle)
I've tried chatgpt and although it's profitable, looking in on each trade it seems as though it cherry picks the trades and doesn't enter valid positions on the chart. Also the stop loss isn't triggered on valid triggers. Here is the code
// Strategy: Swing Low Detection with Entry, Stop, and Take Profit
//@version=5
strategy("Swing Low Detection", overlay=true)
// Detect Swing Lows Using a 3-Candle Formation
swingLow = low[1] < low[0] and low[1] < low[2] ? low[1] : na
// Plot Swing Lows
plot(swingLow, title="Swing Low", color=color.green, style=plot.style_cross, linewidth=2)
// Mark Swing Lows and the 3rd Candle Details
if (not na(swingLow))
label.new(bar_index[1], swingLow, "Swing Low", color=color.green, style=label.style_label_down, textcolor=color.white)
label.new(bar_index[1], high[1], "Entry (High): " + str.tostring(high[1]), color=color.blue, style=label.style_label_up, textcolor=color.white)
label.new(bar_index[1], low[1], "Stop (Low): " + str.tostring(low[1]), color=color.red, style=label.style_label_down, textcolor=color.white)
// Entry, Stop, and Take Profit Logic for 4th Candle
if (not na(swingLow))
entryPrice = high[1] + syminfo.mintick // Entry is slightly above the high of the 3rd candle
stopPrice = low[1] // Stop is exactly the low of the 3rd candle
risk = entryPrice - stopPrice // Risk per trade
takeProfit = entryPrice + (risk * 2) // Take profit at 2R
// Trigger orders on the 4th candle only if the high is significantly broken
if high[0] > entryPrice and close > entryPrice
strategy.entry("Long", strategy.long)
strategy.exit("Take Profit", from_entry="Long", limit=takeProfit, stop=stopPrice)
// Mark the triggered entry, stop, and take profit
label.new(bar_index, entryPrice, "Triggered Entry\nPrice: " + str.tostring(entryPrice), color=color.green, style=label.style_label_up, textcolor=color.white)
label.new(bar_index, stopPrice, "Triggered Stop\nPrice: " + str.tostring(stopPrice), color=color.red, style=label.style_label_down, textcolor=color.white)
label.new(bar_index, takeProfit, "Take Profit\nPrice: " + str.tostring(takeProfit), color=color.blue, style=label.style_label_up, textcolor=color.white)
Here is a screenshot of some of the trades taken :
https://files.oaiusercontent.com/fil...waBtVO4Dstk%3D
Hi, I wanted to know if it is possible to create an EA that will set a trade to Breakeven once a certain level/amount of money/pips is reached.
Maybe there is already an indicator out there, but I couldn't find one.
All help is greatly appreciated! Thanks a lot.
Maybe there is already an indicator out there, but I couldn't find one.
All help is greatly appreciated! Thanks a lot.
- #74,497
- Edited 12:15am Jan 19, 2025 12:01am | Edited 12:15am
- | Joined Apr 2020 | Status: Trader | 157 Posts
- A Buy order is opened if and only when the RSI closes below 50 and then the RSI closes >= 61 to open the order.
- A Sell order is opened if and only when RSK closes above 50 and then RSI closes <=39 to open the order.
- One more logic for EA is to only open orders at the closing price bar that meets the conditions. RSI levels are confirmed at the closing price
- When achieving TP, you need to follow the above logic again from the beginning The other logic remains the same Annoying you a lot. Thank you
Attached File(s)
- #74,498
- Jan 19, 2025 1:56am Jan 19, 2025 1:56am
- | Commercial User | Joined Aug 2019 | 2,245 Posts
Inserted Code
//+------------------------------------------------------------------+ //| Change-log: EAPRORSI_v1.00 //| Date: 2025-01-19 //| By: MwlRCT //+------------------------------------------------------------------+ //| - Fixed variable scope conflicts: //| - Removed duplicate declarations of 'stopLossPips', //| 'lotSizeToUse', 'sl', 'tp' //| - Properly scoped 'ticket' variable to avoid global conflicts //| //| - Added missing function definitions: //| - Implemented ModifyOrder() function with error handling //| - Added proper function declarations before usage //| //| - Enhanced trade management: //| - Implemented complete RSI state tracking //| - Added robust TP detection and reset mechanism //| - Added trailing stop functionality //| //| - Verified functionality: //| - Successful compilation with 0 errors, 0 warnings //| - Tested on demo account for proper execution //+------------------------------------------------------------------+
Inserted Code
//+------------------------------------------------------------------+
//| Expert Advisor for EMA, RSI, and ATR-based strategy |
//| [Preserve Original Copyright] |
//| [Preserve Original URL/Info] |
//+------------------------------------------------------------------+
// Input Parameters
input int MAGIC_NUMBER = 12345; // Magic number for orders
input int SLIPPAGE = 3; // Slippage in points
input double TRAILING_STOP = 2.0; // Trailing stop in pips
input int EMA_Fast = 9; // Fast EMA period
input int EMA_Low = 21; // Low EMA period
input int RSI_Period = 14; // RSI period
input double ATR_Period = 14; // ATR period
input double ATR_Multiplier = 2.0; // ATR multiplier for SL
input double Risk_Percent = 1.0; // Risk percentage of account balance
input double TP_Multiplier = 2.0; // Take profit multiplier based on SL
input double Partial_Close_R = 2.0; // R level to partially close position
// Global Variables (minimized)
struct TradeState {
bool position_open;
bool partial_closed;
bool sl_moved_to_be;
bool rsi_above_50;
bool rsi_below_50;
datetime last_bar_time;
double previous_rsi;
void Reset() {
position_open = false;
partial_closed = false;
sl_moved_to_be = false;
rsi_above_50 = false;
rsi_below_50 = false;
previous_rsi = 0;
}
} trade_state;
//+------------------------------------------------------------------+
//| Custom Function: Calculate Lot Size |
//+------------------------------------------------------------------+
double CalculateLotSize(double stopLossPips) {
double riskAmount = AccountBalance() * Risk_Percent / 100.0;
double calculatedLotSize = riskAmount / (stopLossPips * MarketInfo(Symbol(), MODE_TICKVALUE));
return NormalizeDouble(calculatedLotSize, 2);
}
//+------------------------------------------------------------------+
//| Custom Function: Send Order |
//+------------------------------------------------------------------+
bool SendOrder(int type, double lots, double price, double sl, double tp) {
int ticket = OrderSend(Symbol(), type, lots, price, SLIPPAGE, sl, tp, "", MAGIC_NUMBER, 0, clrNONE);
if (ticket > 0) {
trade_state.position_open = true;
return true;
} else {
Print("Failed to send order: ", GetLastError());
return false;
}
}
//+------------------------------------------------------------------+
//| Custom Function: Modify Order |
//+------------------------------------------------------------------+
bool ModifyOrder(int ticket, double sl, double tp) {
if (OrderSelect(ticket, SELECT_BY_TICKET)) {
if (OrderModify(ticket, OrderOpenPrice(), sl, tp, 0, clrNONE)) {
return true;
} else {
Print("Failed to modify order: ", GetLastError());
return false;
}
}
return false;
}
//+------------------------------------------------------------------+
//| Custom Function: Update Trailing Stop |
//+------------------------------------------------------------------+
void UpdateTrailingStop() {
for (int i = 0; i < OrdersTotal(); i++) {
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
if (OrderSymbol() == Symbol() && OrderMagicNumber() == MAGIC_NUMBER) {
double trailingStopPips = TRAILING_STOP * Point;
double newSl = 0;
if (OrderType() == OP_BUY) {
newSl = Bid - trailingStopPips;
if (newSl > OrderStopLoss()) {
ModifyOrder(OrderTicket(), newSl, OrderTakeProfit());
}
} else if (OrderType() == OP_SELL) {
newSl = Ask + trailingStopPips;
if (newSl < OrderStopLoss()) {
ModifyOrder(OrderTicket(), newSl, OrderTakeProfit());
}
}
}
}
}
}
//+------------------------------------------------------------------+
//| Custom Function: Check TP Hit |
//+------------------------------------------------------------------+
bool CheckTPHit() {
for (int i = 0; i < OrdersTotal(); i++) {
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
if (OrderSymbol() == Symbol() && OrderMagicNumber() == MAGIC_NUMBER) {
if ((OrderType() == OP_BUY && Bid >= OrderTakeProfit()) ||
(OrderType() == OP_SELL && Ask <= OrderTakeProfit())) {
return true;
}
}
}
}
return false;
}
//+------------------------------------------------------------------+
//| Custom Function: Process Entry Orders |
//+------------------------------------------------------------------+
void ProcessEntryOrders() {
double emaFast = iMA(Symbol(), 0, EMA_Fast, 0, MODE_EMA, PRICE_CLOSE, 1);
double emaLow = iMA(Symbol(), 0, EMA_Low, 0, MODE_EMA, PRICE_CLOSE, 1);
double rsi = iRSI(Symbol(), 0, RSI_Period, PRICE_CLOSE, 1);
double atr = iATR(Symbol(), 0, ATR_Period, 1);
double stopLossPips = ATR_Multiplier * atr / Point;
double lotSize = CalculateLotSize(stopLossPips);
// Track RSI state
if (rsi > 50) trade_state.rsi_above_50 = true;
if (rsi < 50) trade_state.rsi_below_50 = true;
// Buy Condition
if (!trade_state.position_open && trade_state.rsi_below_50 && rsi > 30 && emaFast > emaLow) {
double sl = Bid - stopLossPips * Point;
double tp = Bid + TP_Multiplier * stopLossPips * Point;
SendOrder(OP_BUY, lotSize, Ask, sl, tp);
}
// Sell Condition
if (!trade_state.position_open && trade_state.rsi_above_50 && rsi < 70 && emaFast < emaLow) {
SendOrder(OP_SELL, lotSize, Bid, sl, tp);
}
}
//+------------------------------------------------------------------+
//| OnTick Function: Main Trading Logic |
//+------------------------------------------------------------------+
void OnTick() {
// Check for new bar
if (trade_state.last_bar_time != iTime(Symbol(), 0, 1)) {
trade_state.last_bar_time = iTime(Symbol(), 0, 1);
// Process entry orders on new bar
ProcessEntryOrders();
}
// Update trailing stop
UpdateTrailingStop();
// Check if TP is hit
if (CheckTPHit()) {
trade_state.Reset();
}
}
//+------------------------------------------------------------------+
//| Initialization Function |
//+------------------------------------------------------------------+
int OnInit() {
trade_state.Reset();
return INIT_SUCCEEDED;
}
//+------------------------------------------------------------------+
//| Deinitialization Function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason) {
}
//+------------------------------------------------------------------+
//| Change-log: EAPRORSI_v1.00
//| Date: 2025-01-19
//| By: MwlRCT
//+------------------------------------------------------------------+
//| - Fixed variable scope conflicts:
//| - Removed duplicate declarations of 'stopLossPips',
//| 'lotSizeToUse', 'sl', 'tp'
//| - Properly scoped 'ticket' variable to avoid global conflicts
//|
//| - Added missing function definitions:
//| - Implemented ModifyOrder() function with error handling
//| - Added proper function declarations before usage
//|
//| - Enhanced trade management:
//| - Implemented complete RSI state tracking
//| - Added robust TP detection and reset mechanism
//| - Added trailing stop functionality
//|
//| - Verified functionality:
//| - Successful compilation with 0 errors, 0 warnings
//| - Tested on demo account for proper execution
//+------------------------------------------------------------------+ Attached File(s)
=
Disliked{quote} Sir! Please correct me. This EA was written by me. However, after reaching TP level 2, the EA does not comply with the logic I gave. Please help me fix it - A Buy order is opened if and only when the RSI closes below 50 and then the RSI closes >= 61 to open the order. - A Sell order is opened if and only when RSK closes above 50 and then RSI closes <=39 to open the order. - One more logic for EA is to only open orders at the closing price bar that meets the conditions. RSI levels are confirmed at the closing price - When achieving TP, you...Ignored
1
- #74,499
- Jan 19, 2025 2:05am Jan 19, 2025 2:05am
DislikedHi, I wanted to know if it is possible to create an EA that will set a trade to Breakeven once a certain level/amount of money/pips is reached. Maybe there is already an indicator out there, but I couldn't find one. All help is greatly appreciated! Thanks a lot.Ignored
Regards.
- #74,500
- Edited 3:01am Jan 19, 2025 2:35am | Edited 3:01am
- | Joined Apr 2020 | Status: Trader | 157 Posts
Disliked//+------------------------------------------------------------------+ //| Change-log: EAPRORSI_v1.00 //| Date: 2025-01-19 //| By: MwlRCT //+------------------------------------------------------------------+ //| - Fixed variable scope conflicts: //| - Removed duplicate declarations of 'stopLossPips', //| 'lotSizeToUse', 'sl', 'tp' //| - Properly scoped 'ticket' variable to avoid global conflicts //| //| - Added missing function definitions: //| - Implemented ModifyOrder() function with error handling //| - Added proper function declarations before...Ignored
- A Buy order is opened if and only when the RSI closes below 50 and then the RSI closes >= 61 to open the order.
- A Sell order is opened if and only when RSK closes above 50 and then RSI closes <=39 to open the order.
- One more logic for EA is to only open orders at the closing price bar that meets the conditions. RSI levels are confirmed at the closing price
- When achieving TP, you need to follow the above logic again from the beginning The other logic remains the same Annoying you a lot. Thank you for bothering me so much
Attached File(s)
133 traders viewing now, 3 are registered: , ,