HELP DARE UN ORARIO BEN DEFINITO PER OPERARE

Sezione dedicata a metatrader (ed altre piattaforme) ed al suo linguaggio di programmazione per il trading automatico

Moderator: Dainesi

Post Reply
GICOFX
Posts: 10
Joined: 10/01/2016, 18:24

HELP DARE UN ORARIO BEN DEFINITO PER OPERARE

Post by GICOFX » 11/09/2017, 19:16

Salve a tutti con un software, mi sono creato degli EA ,ma non riesco a trovare il modo per inserire un orario ben definito in modo che non apra altre posizioni se gia ce ne sono in esssere da una ora x ad un ora y ...chi puo' aiutarmi? magari stasera posto le righe di programa che dite ? grazie cmq

Sponsor

Sponsor
 

User avatar
PlSoft
Posts: 114
Joined: 20/12/2015, 21:12
Location: Suzzara

Re: HELP DARE UN ORARIO BEN DEFINITO PER OPERARE

Post by PlSoft » 11/09/2017, 21:20

Ciao

Questa è la routine che ti serve. Aggiungi il tuo codice e fammi sapere. :green:

extern bool InOut = true; // True = opero all'interno dell'orario - False = opero orario esterno
extern int Start_Time = 0; // Time to allow trading to start ( hours of 24 hr clock ) 0 for both disables
extern int Finish_Time = 0; // Time to stop trading ( hours of 24 hr clock ) 0 for both disables


if(InOut == true)
{
if(AllowTradesByTime()== false) { my codice; }
}else{
if(AllowTradesByTime()== true) { my codice; }
}

// ------------------------------------------------------------------------------------------------
// AllowTradesByTime
// ------------------------------------------------------------------------------------------------
bool AllowTradesByTime()
{
int Current_Time = TimeHour(TimeCurrent());

if (Start_Time == 0) Start_Time = 24; if (Finish_Time == 0) Finish_Time = 24; if (Current_Time == 0) Current_Time = 24;

if ( Start_Time < Finish_Time )
if ( (Current_Time < Start_Time) || (Current_Time >= Finish_Time) ) return(false);

if ( Start_Time > Finish_Time )
if ( (Current_Time < Start_Time) && (Current_Time >= Finish_Time) ) return(false);

return(true);

}

GICOFX
Posts: 10
Joined: 10/01/2016, 18:24

Re: HELP DARE UN ORARIO BEN DEFINITO PER OPERARE

Post by GICOFX » 12/09/2017, 10:42

Grazie ma di codice n capisco na mazza nel senso che non ho il tempo per impararlo ,se vuoi ti posto il codice dell'ea e se me lo implementi tu le righe che mi hai postato altrimenti io farei solo casini nell'EA...come posto un allegato ??? :help:

GICOFX
Posts: 10
Joined: 10/01/2016, 18:24

Re: HELP DARE UN ORARIO BEN DEFINITO PER OPERARE

Post by GICOFX » 12/09/2017, 11:21

#property copyright "StrategyQuant.com"
#property link "http://www.StrategyQuant.com"

//+------------------------------------------------------------------+
// -- SL/PT Parameters
//+------------------------------------------------------------------+
extern string __s2 = "----- SL/PT Parameters ----------------------";

// this is the minimum and maximum value for PT & SL used,
// any bigger or smaller value will be capped to this range
extern double MinimumSLPT = 30;
extern double MaximumSLPT = 300;

//+------------------------------------------------------------------+
// -- Money Management Parameters
//+------------------------------------------------------------------+
extern string __s6 = "----- Money Management Parameters -----------";
extern bool UseMoneyManagement = false;
extern double Lots = 0.1;
extern int LotsDecimals = 2;
extern double RiskInPercent = 2.0;
extern double MaximumLots = 0.5;
extern bool UseFixedMoney = false;
extern double RiskInMoney = 100.0;

//+------------------------------------------------------------------+
// -- Trading Logic Settings
//+------------------------------------------------------------------+
extern string __s7 = "----- Trading Logic Settings ----------------";
extern int MaxTradesPerDay = 0; // 0 means unlimited
extern bool LimitSignalsToRange = false;
extern string TimeRangeFrom = "08:00";
extern string TimeRangeTo = "16:00";
extern bool ExitAtEndOfRange = false;
extern bool ExitAtEndOfDay = false;
extern string ExitTimeEOD = "00:00";
extern bool ExitOnFriday = true;
extern string ExitTimeOnFriday = "00:00";

extern int OpenBarDelay = 0; // open bar delay in minutes
// it can be used for Daily strategies to trigger trading a few minutes later -
// because brokers sometimes have technical delay after midnight and we have to postpone order

extern bool ModifyInsteadOfReplacing = true;

extern bool TradeLong = true;
extern bool TradeShort = true;

//+------------------------------------------------------------------+
// -- Trading Date Parameters
//+------------------------------------------------------------------+
extern string __s8 = "----- Trading Date Parameters ---------------";
extern bool TradeSunday = true;
extern bool TradeMonday = true;
extern bool TradeTuesday = true;
extern bool TradeWednesday = true;
extern bool TradeThursday = true;
extern bool TradeFriday = true;
extern bool TradeSaturday = true;


//+------------------------------------------------------------------+
// -- Other Parameters
//+------------------------------------------------------------------+
extern string __s9 = "----- Other Parameters ----------------------";
extern int MaxSlippage = 3;
extern string CustomComment = "Created strategy 1";
extern int MagicNumber = 12345;
extern bool EmailNotificationOnTrade = false;
extern bool DisplayInfoPanel = true;

//+------------------------------------------------------------------+
// -- Other Hidden Parameters
//+------------------------------------------------------------------+
int MinDistanceOfStopFromPrice = 5.0;
double gPointPow = 0;
double gPointCoef = 0;
double gbSpread = 3.0;
double brokerStopDifference = 0;
string eaStopDifference = "";
double eaStopDifferenceNumber = 0;
int lastHistoryPosChecked = 0;
int lastHistoryPosCheckedNT = 0;
string currentTime = "";
string lastTime = "";
bool tradingRangeReverted = false;
string sqLastPeriod;
bool sqIsBarOpen;
int LabelCorner = 1;
int OffsetHorizontal = 5;
int OffsetVertical = 20;
color LabelColor = White;
int lastDeletedOrderTicket = -1;
bool rettmp;
bool ReplacePendingOrders = false;

/**
* add your own parameters that will be included in every EA
* into file /code/CustomParametersMT4.mq4
*/
//extern bool TradeOnHour1 = true;
bool firstCall = true;

//+------------------------------------------------------------------+
// -- Functions
//+------------------------------------------------------------------+

int start() {

drawStats();

if(!customStart()) return(0);

if(manageTrades()) {
// we are within trading range hours (if set)

//-------------------------------------------
// ENTRY RULES

// LONG: (ATR(14) > ATR(80))
if(TradeLong) {
bool LongEntryCondition = (iATR(NULL, 0, 14, 1) > iATR(NULL, 0, 80, 1));
if(LongEntryCondition == true) {
openPosition(1);
}
}

// SHORT: (ATR(14) < ATR(20))
if(TradeShort) {
bool ShortEntryCondition = (iATR(NULL, 0, 14, 1) < iATR(NULL, 0, 20, 1));
if(ShortEntryCondition == true) {
openPosition(-1);
}
}
}

if(getMarketPosition() != 0) {
manageStop();
}

return(0);
}

//+------------------------------------------------------------------+

int init() {
Log("--------------------------------------------------------");
Log("Starting the EA");

double realDigits;
if(Digits < 2) {
realDigits = 0;
} else if (Digits < 4) {
realDigits = 2;
} else {
realDigits = 4;
}

gPointPow = MathPow(10, realDigits);
gPointCoef = 1/gPointPow;

double brokerStopDifferenceNumber = MarketInfo(Symbol(),MODE_STOPLEVEL)/MathPow(10, Digits);
brokerStopDifference = gPointPow*brokerStopDifferenceNumber;

eaStopDifferenceNumber = MinDistanceOfStopFromPrice/gPointPow;

eaStopDifference = DoubleToStr(MinDistanceOfStopFromPrice, 2);
Log("Broker Stop Difference: ",DoubleToStr(brokerStopDifference, 2),", EA Stop Difference: ",eaStopDifference);

if(DoubleToStr(brokerStopDifference, 2) != eaStopDifference) {
Log("WARNING! EA Stop Difference is different from real Broker Stop Difference, the backtest results in MT4 could be different from results of Genetic Builder!");

if(eaStopDifferenceNumber < brokerStopDifferenceNumber) {
eaStopDifferenceNumber = brokerStopDifferenceNumber;
}
}

string brokerSpread = DoubleToStr((Ask - Bid)*gPointPow, 2);
string strGbSpread = DoubleToStr(gbSpread, 2);
Log("Broker spread: ",brokerSpread,", Genetic Builder test spread: ",strGbSpread);

if(strGbSpread != brokerSpread) {
Log("WARNING! Real Broker spread is different from spread used in Genetic Builder, the backtest results in MT4 could be different from results of Genetic Builder!");
}

if(TimeStringToDateTime(TimeRangeTo) < TimeStringToDateTime(TimeRangeFrom)) {
tradingRangeReverted = true;
Log("Trading range s reverted, from: ", TimeRangeFrom," to ", TimeRangeTo);
} else {
tradingRangeReverted = false;
}

Log("--------------------------------------------------------");

customInit();

if(DisplayInfoPanel) {
ObjectCreate("line1", OBJ_LABEL, 0, 0, 0);
ObjectSet("line1", OBJPROP_CORNER, LabelCorner);
ObjectSet("line1", OBJPROP_YDISTANCE, OffsetVertical + 0 );
ObjectSet("line1", OBJPROP_XDISTANCE, OffsetHorizontal);
ObjectSetText("line1", "Created strategy 1", 9, "Tahoma", LabelColor);

ObjectCreate("linec", OBJ_LABEL, 0, 0, 0);
ObjectSet("linec", OBJPROP_CORNER, LabelCorner);
ObjectSet("linec", OBJPROP_YDISTANCE, OffsetVertical + 16 );
ObjectSet("linec", OBJPROP_XDISTANCE, OffsetHorizontal);
ObjectSetText("linec", "Generated by StrategyQuant 3.8.2", 8, "Tahoma", LabelColor);

ObjectCreate("line2", OBJ_LABEL, 0, 0, 0);
ObjectSet("line2", OBJPROP_CORNER, LabelCorner);
ObjectSet("line2", OBJPROP_YDISTANCE, OffsetVertical + 28);
ObjectSet("line2", OBJPROP_XDISTANCE, OffsetHorizontal);
ObjectSetText("line2", "------------------------------------------", 8, "Tahoma", LabelColor);

ObjectCreate("lines", OBJ_LABEL, 0, 0, 0);
ObjectSet("lines", OBJPROP_CORNER, LabelCorner);
ObjectSet("lines", OBJPROP_YDISTANCE, OffsetVertical + 44);
ObjectSet("lines", OBJPROP_XDISTANCE, OffsetHorizontal);
ObjectSetText("lines", "Last Signal: -", 9, "Tahoma", LabelColor);

ObjectCreate("lineopl", OBJ_LABEL, 0, 0, 0);
ObjectSet("lineopl", OBJPROP_CORNER, LabelCorner);
ObjectSet("lineopl", OBJPROP_YDISTANCE, OffsetVertical + 60);
ObjectSet("lineopl", OBJPROP_XDISTANCE, OffsetHorizontal);
ObjectSetText("lineopl", "Open P/L: -", 8, "Tahoma", LabelColor);

ObjectCreate("linea", OBJ_LABEL, 0, 0, 0);
ObjectSet("linea", OBJPROP_CORNER, LabelCorner);
ObjectSet("linea", OBJPROP_YDISTANCE, OffsetVertical + 76);
ObjectSet("linea", OBJPROP_XDISTANCE, OffsetHorizontal);
ObjectSetText("linea", "Account Balance: -", 8, "Tahoma", LabelColor);

ObjectCreate("lineto", OBJ_LABEL, 0, 0, 0);
ObjectSet("lineto", OBJPROP_CORNER, LabelCorner);
ObjectSet("lineto", OBJPROP_YDISTANCE, OffsetVertical + 92);
ObjectSet("lineto", OBJPROP_XDISTANCE, OffsetHorizontal);
ObjectSetText("lineto", "Total profits/losses so far: -/-", 8, "Tahoma", LabelColor);

ObjectCreate("linetp", OBJ_LABEL, 0, 0, 0);
ObjectSet("linetp", OBJPROP_CORNER, LabelCorner);
ObjectSet("linetp", OBJPROP_YDISTANCE, OffsetVertical + 108);
ObjectSet("linetp", OBJPROP_XDISTANCE, OffsetHorizontal);
ObjectSetText("linetp", "Total P/L so far: -", 8, "Tahoma", LabelColor);
}

return(0);
}

//+------------------------------------------------------------------+

int deinit() {
ObjectDelete("line1");
ObjectDelete("linec");
ObjectDelete("line2");
ObjectDelete("lines");
ObjectDelete("lineopl");
ObjectDelete("linea");
ObjectDelete("lineto");
ObjectDelete("linetp");
return(0);
}

//+------------------------------------------------------------------+

double getSpecialSL(double value) {
return(sqRoundToPrice(value));
}

double getSpecialPT(double value) {
return(sqRoundToPrice(value));
}

double getNormalSL(double value) {
return(sqRoundToPrice(value));
}

double getNormalPT(double value) {
return(sqRoundToPrice(value));
}

double getBid() {
return(Bid);
}

double getAsk() {
return(Ask);
}

//+------------------------------------------------------------------+

void manageTradeSLPT() {
}

//+------------------------------------------------------------------+

double getTradeOpenPrice(int tradeDirection) {
RefreshRates();

if(tradeDirection == 1) {
// long
return(Ask);
} else {
// short
return(Bid);
}
}

//+------------------------------------------------------------------+

double getStopLoss(int tradeDirection) {
if(tradeDirection == 1) {
// long
return(checkCorrectMinMaxSLPT(10 * gPointCoef));
} else {
// short
return(checkCorrectMinMaxSLPT(10 * gPointCoef));
}

return(0);
}

//+------------------------------------------------------------------+

double getProfitTarget(int tradeDirection) {
if(tradeDirection == 1) {
// long
return(checkCorrectMinMaxSLPT(20 * gPointCoef));
} else {
// short
return(checkCorrectMinMaxSLPT(20 * gPointCoef));
}

return(0);
}
//+------------------------------------------------------------------+

double getProfitTrailingByTick() {
if (OrderType() == OP_BUY) {
// long
} else if (OrderType() == OP_SELL) {
// short
}

return(0);
}

//+------------------------------------------------------------------+

double getStopTrailingByClose() {
double value = 0;
if (OrderType() == OP_BUY) {

} else if (OrderType() == OP_SELL) {
}

return(value);
}

//+------------------------------------------------------------------+

double getMoveSLValueByTick() {
if (OrderType() == OP_BUY) {
// long
return(10 * gPointCoef);
} else if (OrderType() == OP_SELL) {
// short
return(10 * gPointCoef);
}

return(0);
}


//+------------------------------------------------------------------+

void drawStats() {
// changed recognition of bar open to support also range/renko charts
static datetime tmp;
static double open;

if (tmp != Time[0]) { // } || open != Open[0]) { - this doesn't work with renko charts

bool processBarOpen = true;

if(OpenBarDelay > 0) {
// set bar to open only after X minutes from real open
processBarOpen = false;

int diffInSeconds = TimeCurrent() - Time[0];
if(diffInSeconds >= OpenBarDelay * 60) {
processBarOpen = true;
}
}

if(processBarOpen) {
tmp = Time[0];
open = Open[0];

sqIsBarOpen = true;
}
} else {
sqIsBarOpen = false;
}
/*
// old way of checking for new bar open, doesn't work with range/renko bars
string currentPeriod = sqGetTimeAsStr();
if(currentPeriod == sqLastPeriod) {
sqIsBarOpen = false;
} else {
sqLastPeriod = currentPeriod;
sqIsBarOpen = true;
}
*/
sqTextFillOpens();
if(sqIsBarOpen) {
sqTextFillTotals();
}
}

//+------------------------------------------------------------------+

bool manageTrades() {
if(Bars<30) {
Print("NOT ENOUGH DATA: Less Bars than 30");
return(0);
}

closeTradesAtEndOfRange();

if(!sqIsBarOpen) return(false);

if(getMarketPosition() != 0) {
manageTradeSLPT();
}

if(LimitSignalsToRange && checkInsideTradingRange() == false) {
return(false);
}

if(!isCorrectDayOfWeek(Time[0])) {
return(false);
}

if(MaxTradesPerDay > 0) {
if(getNumberOfTradesToday() >= MaxTradesPerDay) {
return(false);
}
}

return(true);
}

//+------------------------------------------------------------------+

void closeTradesAtEndOfRange() {
if(isSomeOrderActive() != 0) {
if(ExitAtEndOfDay) {
if(ExitTimeEOD == "00:00" || ExitTimeEOD == "0:00") {
closeTradeFromPreviousDay();
} else if(TimeCurrent() >= TimeStringToDateTime(ExitTimeEOD)) {
closeActiveOrders();
closePendingOrders();
}
}

if(ExitOnFriday) {
int dow = TimeDayOfWeek(Time[0]);

if(ExitTimeOnFriday == "00:00" || ExitTimeOnFriday == "0:00") {
if(dow == 6 || dow == 0 || dow == 1) {
closeTradeFromPreviousDay();
}
} else if(dow == 5 && TimeCurrent() >= TimeStringToDateTime(ExitTimeOnFriday)) {
closeActiveOrders();
closePendingOrders();
}
}
}

if(LimitSignalsToRange) {
if(checkInsideTradingRange() == false) {
// we are out of allowed trading hours
if(ExitAtEndOfRange) {
if(tradingRangeReverted == false && TimeCurrent() > TimeStringToDateTime(TimeRangeTo)) {
closeActiveOrders();
closePendingOrders();
} else if(tradingRangeReverted == true && TimeCurrent() > TimeStringToDateTime(TimeRangeTo) && TimeCurrent() < TimeStringToDateTime(TimeRangeFrom)) {
closeActiveOrders();
closePendingOrders();
}
}
}
}
}

//+------------------------------------------------------------------+

double sqRoundToPrice(double number) {
double ticksize = MarketInfo(Symbol(),MODE_TICKSIZE);

return ( NormalizeDouble(MathRound(number/ticksize)*ticksize,Digits) );
}

//+------------------------------------------------------------------+

double gbTrueRange(int period, int index) {
int period1 = period + index-1;
int period2 = period + index;
return (MathMax(High[period1], Close[period2]) - MathMin(Low[period1], Close[period2]));
}

//+------------------------------------------------------------------+

double gbBarRange(int period, int index) {
int period2 = period + index-1;
return (MathAbs(High[period2] - Low[period2]));
}

//+------------------------------------------------------------------+

void openPosition(int tradeDirection) {
if(tradeDirection == 0) return;


if(checkTradeClosedThisBar()) {
return;
}

if(checkTradeClosedThisMinute()) {
return;
}

//---------------------------------------
// get order price
double openPrice = sqRoundToPrice(getTradeOpenPrice(tradeDirection));

//---------------------------------------
// get order type
int orderType;
if(tradeDirection == 1) {
if(getMarketPosition() != 0) return;

orderType = OP_BUY;

} else {
if(getMarketPosition() != 0) return;

orderType = OP_SELL;

}

//---------------------------------------
// add SL/PT
double stopLoss = 0;
double profitTarget = 0;

double SL = sqRoundToPrice(getStopLoss(tradeDirection));
double PT = sqRoundToPrice(getProfitTarget(tradeDirection));

if(SL != 0) {
stopLoss = openPrice - tradeDirection * SL;
}
if(PT != 0) {
profitTarget = openPrice + tradeDirection * PT;
}

string comment = "SQ: "+CustomComment;

double orderLots = getLots(SL*gPointPow);
if(orderLots > MaximumLots) {
orderLots = MaximumLots;
}

//---------------------------------------

if(orderType != OP_BUY && orderType != OP_SELL) {
// it is stop or limit order
double AskOrBid;
if(tradeDirection == 1) { AskOrBid = Ask; } else { AskOrBid = Bid; }

// check if stop/limit price isn't too close
if(NormalizeDouble(MathAbs(openPrice - AskOrBid), Digits) <= NormalizeDouble(eaStopDifferenceNumber, Digits)) {
//Log("stop/limit order is too close to actual price");
return;
}

// check price according to order type
if(orderType == OP_BUYSTOP) {
if(AskOrBid >= openPrice) return;
} else if(orderType == OP_SELLSTOP) {
if(AskOrBid <= openPrice) return;

} else if(orderType == OP_BUYLIMIT) {
if(AskOrBid <= openPrice) return;
} else if(orderType == OP_SELLLIMIT) {
if(AskOrBid >= openPrice) return;
}

// there can be only one active order of the same type
if(checkPendingOrderAlreadyExists(orderType)) {
if(!ReplacePendingOrders) {
return;
} else {

if(!ModifyInsteadOfReplacing || OrderLots() != orderLots) {
// we have to close previous pending order
if(!closePendingOrder()) {
Log("Cannot close existing previous pending order with ticket: ", OrderTicket(),", reason: ", GetLastError());
return;
}

} else {
// we will change previous pending order
if(!changePendingOrder(openPrice, stopLoss, profitTarget)) {
Log("Cannot change existing previous pending order with ticket: ", OrderTicket(),", reason: ", GetLastError());
return;
}
return;
}
}
}
}

// open order with error handling and retries
int ticket = 0;
int retries = 3;
while(true) {
retries--;
if(retries < 0) return;
if(getMarketPosition() != 0) return;

if(sqIsTradeAllowed() == 1) {
ticket = openOrderWithErrorHandling(orderType, orderLots, openPrice, stopLoss, profitTarget, comment, MagicNumber);
if(ticket > 0) {
if(tradeDirection > 0) {
ObjectSetText("lines", "Last Signal: Long, ticket: "+ticket, 8, "Tahoma", LabelColor);
} else {
ObjectSetText("lines", "Last Signal: Short, ticket: "+ticket, 8, "Tahoma", LabelColor);
}
return;
}
}

if(ticket == -130 || ticket == -131) {
// invalid stops or volume, we cannot open the trade
return;
}

Sleep(1000);
}
return;
}

//+------------------------------------------------------------------+

int openOrderWithErrorHandling(int orderType, double orderLots, double openPrice, double stopLoss, double profitTarget, string comment, int magicNumber) {

//---------------------------------------
// send order
int error, ticket;
Log("Opening order, direction: ", orderType,", price: ", openPrice, ", Ask: ", Ask, ", Bid: ", Bid);
ticket = OrderSend(Symbol(), orderType, orderLots, openPrice, MaxSlippage, 0, 0, comment, magicNumber, 0, Green);
if(ticket < 0) {
// order failed, write error to log
error = GetLastError();
Log("Error opening order: ",error, " : ", ErrorDescription(error));
return(-error);
}

rettmp = OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES);
Log("Order opened: ", OrderTicket(), " at price:", OrderOpenPrice());

stopLoss = getSpecialSL(stopLoss);
profitTarget = getSpecialPT(profitTarget);

if(EmailNotificationOnTrade) {
SendMail("GB Strategy - Order opened", getNotificationText());
}

// set up stop loss and profit target");
// It has to be done separately to support ECN brokers
if(stopLoss != 0 || profitTarget != 0) {
Log("Setting SL/PT, SL: ", stopLoss, ", PT: ", profitTarget);
if(OrderModify(ticket, OrderOpenPrice(), stopLoss, profitTarget, 0, 0)) {
Log("Order modified, StopLoss: ", OrderStopLoss(),", Profit Target: ", OrderTakeProfit());
} else {
Log("Error modifying order: ",error, " : ", ErrorDescription(error));
}
}

return(ticket);
}

//+------------------------------------------------------------------+
/**
* manage trade - move SL to break even or trailing stop
*/
void manageStop() {

if(!sqIsBarOpen) return;

double trailingStopValue, moveSLValue;
double orderSL, normalOrderSL, orderOpen;
double close = Close[1];
double tsLevel, newSL;

for(int i=0; i<OrdersTotal(); i++) {
if (OrderSelect(i,SELECT_BY_POS)==true && OrderMagicNumber() == MagicNumber && OrderSymbol() == Symbol()) {

if(OrderType() != OP_BUY && OrderType() != OP_SELL) continue;
if(OrderOpenTime() >= Time[0]) continue; // exit if the order was just opened

//------------------------------
// profit trailing on close
trailingStopValue = getProfitTrailingByTick();
if(trailingStopValue > 0) {
if(OrderType() == OP_BUY) {
tsLevel = close - trailingStopValue;
} else {
tsLevel = close + trailingStopValue;
}
orderSL = OrderStopLoss();
normalOrderSL = getNormalSL(orderSL);
newSL = getSpecialSL(tsLevel);

if(OrderType() == OP_BUY) {
if(isSLCorrect(tsLevel) && (orderSL == 0 || normalOrderSL < tsLevel) && !doublesAreEqual(orderSL, newSL)) {
rettmp = OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0);
}
} else {
if (isSLCorrect(tsLevel) && (orderSL == 0 || normalOrderSL > tsLevel) && !doublesAreEqual(orderSL, newSL)) {
rettmp = OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0);
}
}
}

//--------------------------------------------------------
// manage stop trailing on close
trailingStopValue = getStopTrailingByClose();
if(trailingStopValue > 0) {
orderOpen = OrderOpenPrice();
orderSL = OrderStopLoss();
normalOrderSL = getNormalSL(orderSL);
newSL = getSpecialSL(trailingStopValue);

if(OrderType() == OP_BUY) {
if(isSLCorrect(trailingStopValue) && (orderSL == 0 || normalOrderSL < trailingStopValue) && !doublesAreEqual(orderSL, newSL)) {
rettmp = OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0);
}
} else {
if (isSLCorrect(trailingStopValue) && (orderSL == 0 || normalOrderSL > trailingStopValue) && !doublesAreEqual(orderSL, newSL)) {
rettmp = OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0);
}
}
}

//--------------------------------------------------------
// manage SL 2 BE (by tick)
moveSLValue = getMoveSLValueByTick();
if(moveSLValue > 0) {
orderSL = OrderStopLoss();
normalOrderSL = getNormalSL(orderSL);
orderOpen = OrderOpenPrice();
newSL = getSpecialSL(orderOpen);

if(OrderType() == OP_BUY) {
if(isSLCorrect(orderOpen) && (close - orderOpen >= moveSLValue) && (orderSL == 0 || normalOrderSL < orderOpen) && !doublesAreEqual(orderSL, newSL)) {
rettmp = OrderModify(OrderTicket(), orderOpen, newSL, OrderTakeProfit(), 0);
}
} else {
if (isSLCorrect(orderOpen) && (orderOpen - close >= moveSLValue) && (orderSL == 0 || normalOrderSL > orderOpen) && !doublesAreEqual(orderSL, newSL)) {
rettmp = OrderModify(OrderTicket(), orderOpen, newSL, OrderTakeProfit(), 0);
}
}
}
}
}
}
//+------------------------------------------------------------------+

bool isSLCorrect(double slPrice) {
if(OrderType() == OP_BUY) {
if(slPrice < (Bid-eaStopDifferenceNumber)) {
return(true);
}
} else {
if(slPrice > (Ask+eaStopDifferenceNumber)) {
return(true);
}
}

return(false);
}

//+------------------------------------------------------------------+

bool checkPendingOrderAlreadyExists(int orderType) {
for(int i=0; i<OrdersTotal(); i++) {
if (OrderSelect(i,SELECT_BY_POS)==true && OrderMagicNumber() == MagicNumber && OrderSymbol() == Symbol() && OrderType() == orderType) {
return(true);
}
}
return(false);
}

//+------------------------------------------------------------------+

bool closePendingOrder() {
int ticket = OrderTicket();

if(OrderDelete(ticket)) {
lastDeletedOrderTicket = ticket;
return(true);
}

return(false);
}


//+------------------------------------------------------------------+

bool changePendingOrder(double openPrice, double stopLoss, double profitTarget) {
if(openPrice == OrderOpenPrice() && stopLoss == OrderStopLoss() && profitTarget == OrderTakeProfit()) {
// all values are the same, we don't need to change anything
return(true);
}

if(OrderModify(OrderTicket(), openPrice, stopLoss, profitTarget, 0)) {
return(true);
}

return(false);
}

//+------------------------------------------------------------------+

int getMarketPosition() {
for(int i=0; i<OrdersTotal(); i++) {
if (OrderSelect(i,SELECT_BY_POS)==true && OrderMagicNumber() == MagicNumber && OrderSymbol() == Symbol()) {
if(OrderType() == OP_BUY) {
return(1);
}
if(OrderType() == OP_SELL) {
return(-1);
}
}
}

return(0);
}

//+------------------------------------------------------------------+

bool isMarketLongPosition() {
for(int i=0; i<OrdersTotal(); i++) {
if (OrderSelect(i,SELECT_BY_POS)==true && OrderMagicNumber() == MagicNumber && OrderSymbol() == Symbol()) {
if(OrderType() == OP_BUY) {
return(true);
}
}
}

return(false);
}

//+------------------------------------------------------------------+

bool isMarketShortPosition() {
for(int i=0; i<OrdersTotal(); i++) {
if (OrderSelect(i,SELECT_BY_POS)==true && OrderMagicNumber() == MagicNumber && OrderSymbol() == Symbol()) {
if(OrderType() == OP_SELL) {
return(true);
}
}
}

return(false);
}

//+------------------------------------------------------------------+

bool isSomeOrderActive() {
for(int i=0; i<OrdersTotal(); i++) {
if (OrderSelect(i,SELECT_BY_POS)==true && OrderMagicNumber() == MagicNumber && OrderSymbol() == Symbol()) {
return(true);
}
}

return(false);
}

//+------------------------------------------------------------------+

bool checkItIsPendingOrder() {
if(OrderType() != OP_BUY && OrderType() != OP_SELL) {
return(true);
}
return(false);
}

//+------------------------------------------------------------------+

bool selectOrderByMagicNumber() {
for(int i=0; i<OrdersTotal(); i++) {
if (OrderSelect(i,SELECT_BY_POS)==true && OrderMagicNumber() == MagicNumber && OrderSymbol() == Symbol()) {

return(true);
}
}

return(false);
}

//+------------------------------------------------------------------+

bool selectOpenOrderByMagicNumber() {
for(int i=0; i<OrdersTotal(); i++) {
if (OrderSelect(i,SELECT_BY_POS)==true && OrderMagicNumber() == MagicNumber && OrderSymbol() == Symbol()) {

if(checkItIsPendingOrder()) {
continue;
}

return(true);
}
}

return(false);
}

//+------------------------------------------------------------------+

void closePositionAtMarket() {
RefreshRates();
double priceCP;

if(OrderType() == OP_BUY) {
priceCP = Bid;
} else {
priceCP = Ask;
}

rettmp = OrderClose(OrderTicket(), OrderLots(), priceCP, MaxSlippage);
}

//+------------------------------------------------------------------+

void Log(string s1, string s2="", string s3="", string s4="", string s5="", string s6="", string s7="", string s8="", string s9="", string s10="", string s11="", string s12="" ) {
Print(TimeToStr(TimeCurrent(), TIME_DATE|TIME_SECONDS), " ", s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12);
}

//+------------------------------------------------------------------+

void closeTradeFromPreviousDay() {
for(int i=0; i<OrdersTotal(); i++) {
if (OrderSelect(i,SELECT_BY_POS)==true && OrderMagicNumber() == MagicNumber && OrderSymbol() == Symbol()) {
int orderType = OrderType();

if(TimeToStr(Time[0], TIME_DATE) != TimeToStr(OrderOpenTime(), TIME_DATE)) {
if (orderType == OP_BUY || orderType == OP_SELL) {
closePositionAtMarket();
} else {
closePendingOrder();
}
}
}
}
}

//+------------------------------------------------------------------+

double getHighest(int period, int shift) {
double maxnum = -1000000;

for(int i=shift; i<shift+period; i++) {
if(High > maxnum) {
maxnum = High;
}
}

return(maxnum);
}

//+------------------------------------------------------------------+

double getLowest(int period, int shift) {
double minnum = 1000000;

for(int i=shift; i<shift+period; i++) {
if(Low < minnum) {
minnum = Low;
}
}

return(minnum);
}

//+------------------------------------------------------------------+

bool timeIsLower(datetime dt, int toHour, int toMinute) {
if(toHour == 0 && TimeHour(dt) == 23) return (true);
if(TimeHour(dt) < toHour) return(true);
if(TimeHour(dt) > toHour) return (false);

if(TimeMinute(dt) < toMinute) return (true);
if(TimeMinute(dt) > toMinute) return (false);

return (false);
}

bool timeIsBiggerOrEqual(datetime dt, int toHour, int toMinute) {
if(TimeHour(dt) < toHour) return (false);
if(TimeHour(dt) > toHour) return (true);

if(TimeMinute(dt) < toMinute) return (false);
if(TimeMinute(dt) >= toMinute) return (true);

return (false);
}

//+------------------------------------------------------------------+

double getHighestInRange(int fromHour, int fromMinute, int toHour, int toMinute) {
int indexTo = -1;
int indexFrom = -1;
int i;

// find index of bar for timeTo
for(i=1; i<=100; i++) {
if(timeIsBiggerOrEqual(Time, toHour, toMinute) && timeIsLower(Time[i+1], toHour, toMinute)) {
indexTo = i;
break;
}
}

if(indexTo == -1) {
Log("Not found indexTo");
return(-1);
}

// find index of bar for timeFrom
for(i=1; i<=100; i++) {
if(i <= indexTo) continue;

if(timeIsBiggerOrEqual(Time, fromHour, fromMinute) && timeIsLower(Time[i+1], fromHour, fromMinute)) {
indexFrom = i;
break;
}
}

if(indexFrom == -1) {
Log("Not found indexFrom");
return(0);
}

double value = -10000.0;

for(i=indexTo; i<=indexFrom; i++) {
value = MathMax(value, iHigh(NULL, 0, i));
}

return(value);
}

//+------------------------------------------------------------------+

double getLowestInRange(int fromHour, int fromMinute, int toHour, int toMinute) {
int indexTo = -1;
int indexFrom = -1;
int i;

// find index of bar for timeTo
for(i=1; i<=100; i++) {
if(timeIsBiggerOrEqual(Time, toHour, toMinute) && timeIsLower(Time[i+1], toHour, toMinute)) {
indexTo = i;
break;
}
}

if(indexTo == -1) {
Log("Not found indexTo");
return(-1);
}

// find index of bar for timeFrom
for(i=1; i<=100; i++) {
if(i <= indexTo) continue;

if(timeIsBiggerOrEqual(Time, fromHour, fromMinute) && timeIsLower(Time[i+1], fromHour, fromMinute)) {
indexFrom = i;
break;
}
}

if(indexFrom == -1) {
Log("Not found indexFrom");
return(0);
}

double value = 100000.0;

for(i=indexTo; i<=indexFrom; i++) {
value = MathMin(value, iLow(NULL, 0, i));
}

return(value);
}

//+------------------------------------------------------------------+

double getTimeRange(int fromHour, int fromMinute, int toHour, int toMinute) {
return(getHighestInRange(fromHour, fromMinute, toHour, toMinute) - getLowestInRange(fromHour, fromMinute, toHour, toMinute));
}

//+------------------------------------------------------------------+

void manageOrdersExpiration() {

currentTime = getPeriodAsStr();
if(currentTime == lastTime) {
return;
}

int barsOpen = 0;
int orderType;
int exitBars = 0;
int expiration = 0;

for(int i=0; i<OrdersTotal(); i++) {
if (OrderSelect(i,SELECT_BY_POS)==true && OrderMagicNumber() == MagicNumber && OrderSymbol() == Symbol()) {
orderType = OrderType();

if (orderType == OP_BUY || orderType == OP_SELL) {
// it is active order
// do nothing
} else {
// it is stop/limit pending order
if(orderType == OP_BUYLIMIT || orderType == OP_BUYSTOP) {
} else if (orderType == OP_SELLLIMIT || orderType == OP_SELLSTOP) {
}
}
}
}

lastTime = currentTime;
}

//+------------------------------------------------------------------+

void closePendingOrders() {
int orderType;

GICOFX
Posts: 10
Joined: 10/01/2016, 18:24

Re: HELP DARE UN ORARIO BEN DEFINITO PER OPERARE

Post by GICOFX » 12/09/2017, 11:22

dove lo implemento ?

GICOFX
Posts: 10
Joined: 10/01/2016, 18:24

Re: HELP DARE UN ORARIO BEN DEFINITO PER OPERARE

Post by GICOFX » 12/09/2017, 12:47

ECCO IL FILE MQL4 qualcuno mi dice dove inserisco le linee di codice inviate da pisoft
Attachments
daxometro01.mq4
(70.5 KiB) Downloaded 4 times

User avatar
PlSoft
Posts: 114
Joined: 20/12/2015, 21:12
Location: Suzzara

Re: HELP DARE UN ORARIO BEN DEFINITO PER OPERARE

Post by PlSoft » 12/09/2017, 21:01

Ciao

Il file che hai pubblicato già prevede le aperture in una fascia prestabilita.
Come si legge dall'immagine la variabile in riga 41 { LimitSignalsToRange = true } obbliga l' expert ad acquistare nella fascia oraria
dalle ore 08.00 { TimeRangeFrom = 08:00 } alle ore 16:00 { TimeRangeTo = 16:00 }
Attachments
8.68.JPG
8.68.JPG (41.95 KiB) Viewed 95 times

GICOFX
Posts: 10
Joined: 10/01/2016, 18:24

Re: HELP DARE UN ORARIO BEN DEFINITO PER OPERARE

Post by GICOFX » 13/09/2017, 18:27

gRAZIE PIsoft quindi mi basta cambiare il valore orario per gli acquisti in quell'arco temporale GRazzzie !!!!!!

GICOFX
Posts: 10
Joined: 10/01/2016, 18:24

Re: HELP DARE UN ORARIO BEN DEFINITO PER OPERARE

Post by GICOFX » 13/09/2017, 18:29

GICOFX wrote:
13/09/2017, 18:27
gRAZIE PIsoft quindi mi basta cambiare il valore orario per gli acquisti in quell'arco temporale GRazzzie !!!!!!
scusa ma come posso fare xke' mi appaiano quandoo metto l'ea nel grafico,cioe' intendevo invece di agire ogni volta sulle righe di programma ,avere degli input che si possano cambiare facilmente quando si installa sul grafico

User avatar
PlSoft
Posts: 114
Joined: 20/12/2015, 21:12
Location: Suzzara

Re: HELP DARE UN ORARIO BEN DEFINITO PER OPERARE

Post by PlSoft » 14/09/2017, 7:02

Premi il tasto DX del mouse e alla voce Consiglieri esperti premi proprietà, appare il cruscotto da lì cambi i parametri.
Ciao

Post Reply

Who is online

Users browsing this forum: No registered users and 2 guests