Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //+------------------------------------------------------------------+
- //| ashix EA
- //|
- //| Generated by StrategyQuant 3.9.66 for MetaTrader
- //| Generated at 06/19/2018 21:06
- //+------------------------------------------------------------------+
- #property copyright "StrategyQuant.com"
- #property link "http://www.StrategyQuant.com"
- #include <Expert/Expert.mqh>
- #include <Trade/SymbolInfo.mqh>
- #include <Trade/OrderInfo.mqh>
- #include <Trade/HistoryOrderInfo.mqh>
- #include <Trade/PositionInfo.mqh>
- #include <Trade/DealInfo.mqh>
- #include <Trade/TerminalInfo.mqh>
- #include <Object.mqh>
- #include <MovingAverages.mqh>
- const int SLPTTYPE_RANGE = 0;
- const int SLPTTYPE_LEVEL = 1;
- //+------------------------------------------------------------------+
- // -- Variables
- //+------------------------------------------------------------------+
- int MagicNumber = 12345;
- //+------------------------------------------------------------------+
- // -- SQ Variables
- // - add word "extern" in front of the variable you want
- // to make configurable
- //+------------------------------------------------------------------+
- //extern int Expert_ID = 1234;
- struct Indicator {
- string name;
- int handle;
- int bufferIndex;
- };
- Indicator indys[];
- struct LastClosedTrade {
- string symbol;
- int magicNumber;
- datetime closeTime;
- };
- LastClosedTrade lastClosedTrades[];
- MqlTick latest_price; // To be used for getting recent/latest price quotes
- MqlTradeRequest mrequest; // To be used for sending our trade requests
- MqlTradeResult mresult; // To be used to get our trade results
- MqlRates mrate[]; // To be used to store the prices, volumes and spread of each bar
- CTerminalInfo terminalInfo;
- string sqStrategyName = "ashix";
- datetime startTime = TimeCurrent();
- datetime lastCheckedTradeTime = startTime;
- extern bool sqDisplayInfoPanel = true;
- int sqLabelCorner = 1;
- int sqOffsetHorizontal = 5;
- int sqOffsetVertical = 20;
- color sqLabelColor = clrWhite;
- int magicNumber;
- int minBars = 30;
- int sqMaxSlippage;
- int sqVerboseMode;
- int sqMaxRetries = 5;
- double gPointPow = 0;
- double gPointCoef = 0;
- int deviationPoints = 10;
- int sqTicket = 1;
- datetime lastBarTime;
- bool _sqIsBarOpen;
- string valueIdentificationSymbol = "";
- //+------------------------------------------------------------------+
- // -- Functions
- //+------------------------------------------------------------------+
- //+------------------------------------------------------------------+
- //| Expert initialization function |
- //+------------------------------------------------------------------+
- int OnInit(){
- VerboseLog("--------------------------------------------------------");
- VerboseLog("Starting the EA");
- //initMagicNumber();
- if(!initIndicators()) return(INIT_FAILED);
- double realDigits = _Digits;
- if(realDigits > 0 && realDigits != 2 && realDigits != 4) {
- realDigits -= 1;
- }
- gPointPow = MathPow(10, realDigits);
- gPointCoef = 1/gPointPow;
- //VerboseLog("Broker stop level: ", SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL));
- VerboseLog("--------------------------------------------------------");
- if(sqDisplayInfoPanel) {
- sqInitInfoPanel();
- }
- return(INIT_SUCCEEDED);
- }
- //+------------------------------------------------------------------+
- //| Expert deinitialization function |
- //+------------------------------------------------------------------+
- void OnDeinit(const int reason)
- {
- sqDeinitInfoPanel();
- }
- //+------------------------------------------------------------------+
- //| Expert tick function |
- //+------------------------------------------------------------------+
- void OnTick() {
- //--- Do we have enough bars to work with?
- if(Bars(_Symbol,_Period) < minBars) { // if total bars is less than minBars
- Alert(StringFormat("NOT ENOUGH DATA: Less Bars than %d", minBars));
- return;
- }
- if(!SymbolInfoTick(_Symbol, latest_price)) {
- Alert("Error getting the latest price quote - error:",GetLastError(),"!!");
- return;
- }
- //--- Get the details of the latest 2 bars
- if(CopyRates(_Symbol, _Period, 0, 2, mrate) < 2) {
- Alert("Error copying rates/history data - error:", GetLastError(), "!!");
- ResetLastError();
- return;
- }
- ZeroMemory(mrequest); // Initialization of mrequest structure
- checkBarOpen();
- updateLastTrades();
- sqTextFillOpens();
- if(_sqIsBarOpen) {
- sqTextFillTotals();
- }
- sqManagePositions();
- ulong _ticket;
- //------------------------
- // Rule: call
- //------------------------
- if (sqHeikenAshi("NULL",0, "Open", 1) < sqHeikenAshi("NULL",0, "Close", 1))
- {
- // Action #1
- sqLogToFile("Signalsx.txt", "up");
- // Action #2
- sqLogToFile("Signals.txt", "up");
- }
- //------------------------
- // Rule: down
- //------------------------
- if (sqHeikenAshi("NULL",0, "Open", 1) > sqHeikenAshi("NULL",0, "Close", 1))
- {
- // Action #1
- sqLogToFile("Signalsx.txt", "down");
- // Action #2
- sqLogToFile("Signals.txt", "down");
- }
- }
- //+------------------------------------------------------------------+
- //| Trade transaction event |
- //+------------------------------------------------------------------+
- //+------------------------------------------------------------------+
- void updateLastTrades(){
- HistorySelect(lastCheckedTradeTime, TimeCurrent());
- lastCheckedTradeTime = TimeCurrent();
- for(int i=HistoryDealsTotal() - 1; i>=0; i--) {
- ulong ticket = HistoryDealGetTicket(i);
- string dealSymbol = HistoryDealGetString(ticket, DEAL_SYMBOL);
- int dealMagic = HistoryDealGetInteger(ticket, DEAL_MAGIC);
- datetime dealTime = HistoryDealGetInteger(ticket, DEAL_TIME);
- if(HistoryDealGetInteger(ticket, DEAL_ENTRY) != DEAL_ENTRY_OUT) continue;
- int lastTradeIndex = getLastTradeIndex(dealSymbol, dealMagic);
- if(lastTradeIndex >= 0){
- lastClosedTrades[lastTradeIndex].closeTime = dealTime;
- }
- else {
- int prevSize = ArraySize(lastClosedTrades);
- ArrayResize(lastClosedTrades, prevSize + 1, 10);
- lastClosedTrades[prevSize].symbol = dealSymbol;
- lastClosedTrades[prevSize].magicNumber = dealMagic;
- lastClosedTrades[prevSize].closeTime = dealTime;
- }
- }
- }
- //+------------------------------------------------------------------+
- bool sqTradeRecentlyClosed(string symbol, int magicNumber, bool checkThisBar, bool checkThisMinute) {
- string tradeSymbol = correctSymbol(symbol);
- int lastTradeIndex = -1;
- if(tradeSymbol == "Any" || magicNumber == 0){
- for(int a=0; a<ArraySize(lastClosedTrades); a++){
- if((tradeSymbol == "Any" || lastClosedTrades[a].symbol == symbol) && (magicNumber == 0 || lastClosedTrades[a].magicNumber == magicNumber)){
- if(lastTradeIndex < 0 || lastClosedTrades[a].closeTime > lastClosedTrades[lastTradeIndex].closeTime){
- lastTradeIndex = a;
- }
- }
- }
- }
- else {
- lastTradeIndex = getLastTradeIndex(tradeSymbol, magicNumber);
- }
- if(lastTradeIndex >= 0) {
- if(checkThisBar) {
- if(lastClosedTrades[lastTradeIndex].closeTime >= getTime(0)) {
- // order finished this bar
- return true;
- }
- }
- if(checkThisMinute) {
- string strCurrentTimeMinutes = TimeToString(TimeCurrent(), TIME_DATE | TIME_MINUTES);
- string strCloseTimeMinutes = TimeToString(lastClosedTrades[lastTradeIndex].closeTime, TIME_DATE | TIME_MINUTES);
- if(strCurrentTimeMinutes == strCloseTimeMinutes) {
- // order finished this minute
- return true;
- }
- }
- }
- return false;
- }
- //+------------------------------------------------------------------+
- int getLastTradeIndex(string symbol, int magicNumber){
- for(int a=0; a<ArraySize(lastClosedTrades); a++){
- if(lastClosedTrades[a].symbol == symbol && lastClosedTrades[a].magicNumber == magicNumber) return a;
- }
- return -1;
- }
- //+------------------------------------------------------------------+
- bool initIndicators(){
- for(int a=0; a<ArraySize(indys); a++){
- //--- if the handle is not created
- if(indys[a].handle == INVALID_HANDLE) {
- //--- tell about the failure and output the error code
- Print("Failed to create handle of the indicator, error code %d", GetLastError());
- //--- the indicator is stopped early
- return(false);
- }
- }
- return(true);
- }
- //+------------------------------------------------------------------+
- double sqGetGlobalSL(string symbol, int orderType, double price) {
- return(sqGetSLLevel(symbol, orderType, price, true, 0));
- }
- //+------------------------------------------------------------------+
- double sqGetGlobalPT(string symbol, int orderType, double price) {
- return(sqGetPTLevel(symbol, orderType, price, true, 0));
- }
- //+------------------------------------------------------------------+
- double sqGetValueByIdentification(int idHash) {
- string symbol = valueIdentificationSymbol;
- return(0);
- }
- //+------------------------------------------------------------------+
- void sqManagePositions() {
- for (int cc = PositionsTotal() - 1; cc >= 0; cc--) {
- ulong positionTicket = PositionGetTicket(cc);
- if (PositionSelectByTicket(positionTicket)) {
- sqManageSL2BE(positionTicket);
- sqManageTrailingStop(positionTicket);
- sqManageExitAfterXBars(positionTicket); }
- if(PositionsTotal() <= 0) return;
- }
- if(_sqIsBarOpen) {
- sqManageOrderExpirations();
- }
- }
- //+------------------------------------------------------------------+
- /*
- void initMagicNumber(){
- int Period_ID = 0;
- switch ( Period() )
- {
- case PERIOD_MN1: Period_ID = 9; break;
- case PERIOD_W1: Period_ID = 8; break;
- case PERIOD_D1: Period_ID = 7; break;
- case PERIOD_H4: Period_ID = 6; break;
- case PERIOD_H1: Period_ID = 5; break;
- case PERIOD_M30: Period_ID = 4; break;
- case PERIOD_M15: Period_ID = 3; break;
- case PERIOD_M5: Period_ID = 2; break;
- case PERIOD_M1: Period_ID = 1; break;
- }
- magicNumber = MagicNumber * 10 + Period_ID;//Expert_ID * 10 + Period_ID;
- }
- */
- //+------------------------------------------------------------------+
- void checkBarOpen(){
- datetime currentBarTime = mrate[0].time;
- _sqIsBarOpen = currentBarTime == 0 || currentBarTime != lastBarTime;
- lastBarTime = currentBarTime;
- }
- //+------------------------------------------------------------------+
- bool indyCrossesAbove(string indy1, string indy2, int shift1, int shift2) {
- double buffer1[], buffer2[];
- if(!loadIndicatorValues(buffer1, indy1, 2, shift1) || !loadIndicatorValues(buffer2, indy2, 2, shift2)) return false;
- return buffer1[0] <= buffer2[0] && buffer1[1] > buffer2[1];
- }
- //+------------------------------------------------------------------+
- bool indyCrossesBelow(string indy1, string indy2, int shift1, int shift2) {
- double buffer1[], buffer2[];
- if(!loadIndicatorValues(buffer1, indy1, 2, shift1) || !loadIndicatorValues(buffer2, indy2, 2, shift2)) return false;
- return buffer1[0] >= buffer2[0] && buffer1[1] < buffer2[1];
- }
- //+------------------------------------------------------------------+
- bool crossesAbove(string indy, int shift, double value) {
- double buffer[];
- if(!loadIndicatorValues(buffer, indy, 2, shift)) return false;
- return buffer[0] <= value && buffer[1] > value;
- }
- //+------------------------------------------------------------------+
- bool crossesBelow(string indy, int shift, double value) {
- double buffer[];
- if(!loadIndicatorValues(buffer, indy, 2, shift)) return false;
- return buffer[0] >= value && buffer[1] < value;
- }
- //+------------------------------------------------------------------+
- bool crossesUp(string indy, int shift, double value) {
- double buffer[];
- if(!loadIndicatorValues(buffer, indy, 2, shift)) return false;
- return buffer[0] < value && buffer[1] > value;
- }
- //+------------------------------------------------------------------+
- bool crossesDown(string indy, int shift, double value) {
- double buffer[];
- if(!loadIndicatorValues(buffer, indy, 2, shift)) return false;
- return buffer[0] > value && buffer[1] < value;
- }
- //+------------------------------------------------------------------+
- bool changesUp(string indy, int shift){
- double buffer[];
- if(!loadIndicatorValues(buffer, indy, 3, shift)) return false;
- return buffer[0] > buffer[1] && buffer[1] < buffer[2];
- }
- //+------------------------------------------------------------------+
- bool changesDown(string indy, int shift){
- double buffer[];
- if(!loadIndicatorValues(buffer, indy, 3, shift)) return false;
- return buffer[0] < buffer[1] && buffer[1] > buffer[2];
- }
- //+------------------------------------------------------------------+
- bool sqIsFalling(string indy, int bars, bool allowSameValues, int shift){
- double buffer[];
- bool atLeastOnce = false;
- if(!loadIndicatorValues(buffer, indy, bars, shift)) return false;
- double lastValue = buffer[0];
- for(int a=1; a<bars; a++){
- if(buffer[a] > lastValue || (!allowSameValues && buffer[a] == lastValue)) return false;
- if(buffer[a] < lastValue){
- atLeastOnce = true;
- }
- lastValue = buffer[a];
- }
- return atLeastOnce;
- }
- //+------------------------------------------------------------------+
- bool sqIsRising(string indy, int bars, bool allowSameValues, int shift){
- double buffer[];
- bool atLeastOnce = false;
- if(!loadIndicatorValues(buffer, indy, bars, shift)) return false;
- double lastValue = buffer[0];
- for(int a=1; a<bars; a++){
- if(buffer[a] < lastValue || (!allowSameValues && buffer[a] == lastValue)) return false;
- if(buffer[a] > lastValue){
- atLeastOnce = true;
- }
- lastValue = buffer[a];
- }
- return atLeastOnce;
- }
- //+------------------------------------------------------------------+
- double sqGetIndicatorValue(string indicatorIdentification, int shift) {
- double buffer[];
- if(!loadIndicatorValues(buffer, indicatorIdentification, 1, shift)) return 0;
- return buffer[0];
- }
- //+------------------------------------------------------------------+
- double sqGetIndicatorValue(string indicatorIdentification, int bufferIndex, int shift) {
- double buffer[];
- ResetLastError();
- int index = getIndicatorIndex(indicatorIdentification);
- if(index >= 0) {
- waitForData(indys[index].handle, bufferIndex, shift);
- if(CopyBuffer(indys[index].handle, bufferIndex, shift, 1, buffer) < 0) {
- int lastError = GetLastError();
- PrintFormat("Failed to copy data from the indicator, error code %d", lastError);
- PrintFormat("Error Description: " + ErrorDescription(lastError));
- return(0);
- }
- return buffer[0];
- }
- else {
- PrintFormat("Failed to copy data from the indicator. Indicator '" + indicatorIdentification + "' was not found.");
- return 0;
- }
- }
- //+------------------------------------------------------------------+
- double sqGetIndicatorValue(int handle, int bufferIndex, int shift) {
- double buffer[];
- ResetLastError();
- waitForData(handle, bufferIndex, shift);
- if(CopyBuffer(handle, bufferIndex, shift, 1, buffer) < 0) {
- int lastError = GetLastError();
- PrintFormat("Failed to copy data from the indicator, error code %d", lastError);
- PrintFormat("Error Description: " + ErrorDescription(lastError));
- return(0);
- }
- return buffer[0];
- }
- //+------------------------------------------------------------------+
- /* Waits until indicator data become available */
- void waitForData(int handle, int bufferIndex, int shift){
- double buffer[];
- int i, copied = CopyBuffer(handle, bufferIndex, shift, 1, buffer);
- if(copied <= 0){
- Sleep(10);
- for(i=0; i<100; i++){
- if(BarsCalculated(handle) > 0) break;
- Sleep(10);
- }
- }
- }
- //+------------------------------------------------------------------+
- bool loadIndicatorValues(double& buffer[], string indy, int bars, int shift){
- //--- reset error code
- ResetLastError();
- //--- fill a part of the Buffer array with values from the indicator buffer that has 0 index
- int index = getIndicatorIndex(indy);
- if(index >= 0) {
- if(CopyBuffer(indys[index].handle, indys[index].bufferIndex, shift, bars, buffer) < 0) {
- //--- if the copying fails, tell the error code
- PrintFormat("Failed to copy data from the indicator, error code %d", GetLastError());
- //--- quit with zero result - it means that the indicator is considered as not calculated
- return(false);
- }
- //--- everything is fine
- return(true);
- }
- else {
- ArrayResize(buffer, bars);
- string params[];
- if(!extractParams(indy, params)){
- Print("Unknown indicator '" + indy + "'. Cannot parse params");
- return(false);
- }
- if(StringFind(indy, "sqHeikenAshi", 0) == 0){
- for(int a=0; a<bars; a++){
- int curShift = StringToInteger(params[3]) + shift + bars - 1 - a;
- buffer[a] = sqHeikenAshi(params[0], (ENUM_TIMEFRAMES) StringToInteger(params[1]), params[2], curShift);
- }
- return(true);
- }
- else if(StringFind(indy, "sqDaily", 0) == 0){
- for(int a=0; a<bars; a++){
- int curShift = StringToInteger(params[3]) + shift + bars - 1 - a;
- buffer[a] = sqDaily(params[0], StringToInteger(params[1]), params[2], curShift);
- }
- return(true);
- }
- else return(false);
- }
- }
- //+------------------------------------------------------------------+
- bool extractParams(string wholeString, string &buffer[]){
- int bracketPos = StringFind(wholeString, "(") + 1;
- if(bracketPos < 0) return(false);
- string paramsStr = StringSubstr(wholeString, bracketPos, StringLen(wholeString) - bracketPos - 1);
- StringSplit(paramsStr, StringGetCharacter(",", 0), buffer);
- for(int a=0; a<ArraySize(buffer); a++){
- StringTrimLeft(buffer[a]);
- StringTrimRight(buffer[a]);
- }
- return(true);
- }
- //+------------------------------------------------------------------+
- int getIndicatorIndex(string name){
- for(int a=0; a<ArraySize(indys); a++){
- if(StringCompare(indys[a].name, name, true) == 0){
- return a;
- }
- }
- //Print("Error - Indicator '" + name + "' not found.");
- return -1;
- }
- //+------------------------------------------------------------------+
- string correctSymbol(string symbol){
- return (symbol == NULL || symbol == "NULL" || symbol == "Current") ? Symbol() : symbol;
- }
- //+------------------------------------------------------------------+
- ulong openPosition(ENUM_ORDER_TYPE type, string symbol, double volume, const double price = 0, const double slPrice = 0, const double ptPrice = 0, const int deviation = 100, const string comment = "", const int magicNo = -1, const datetime expiration = NULL, const bool replaceExisting = true){
- // check if pending order exists
- if(sqSelectPendingOrderByType(magicNo, symbol, 0, comment)) {
- if(!replaceExisting) {
- Verbose("Pending Order with these parameters already exists, and replace is not allowed!", " ----------------");
- return(0);
- }
- // close pending order
- Verbose("Deleting previous pending order");
- sqDeletePendingOrder(OrderGetInteger(ORDER_TICKET));
- } else {
- Log("No pending orders of that type");
- }
- Alert("-----SLPT: ", slPrice, ", ", ptPrice);
- ZeroMemory(mrequest);
- double curPrice = price > 0 ? price : SymbolInfoDouble(symbol, type == ORDER_TYPE_BUY ? SYMBOL_BID : SYMBOL_ASK);
- mrequest.action = (type == ORDER_TYPE_BUY_LIMIT || type == ORDER_TYPE_SELL_LIMIT) ? TRADE_ACTION_PENDING : TRADE_ACTION_DEAL; // immediate order execution
- mrequest.price = NormalizeDouble(curPrice,_Digits); // latest ask price
- mrequest.sl = NormalizeDouble(slPrice, _Digits); // Stop Loss
- mrequest.tp = NormalizeDouble(ptPrice, _Digits); // Take Profit
- mrequest.symbol = correctSymbol(symbol); // currency pair
- mrequest.volume = volume; // number of lots to trade
- mrequest.magic = magicNo > 0 ? magicNo : 1234; // Order Magic Number
- mrequest.type = type; // Buy Order
- mrequest.type_filling = ORDER_FILLING_FOK; // Order execution type
- mrequest.deviation = deviation; // Deviation from current price
- mrequest.comment = comment;//StringLen(comment) > 0 ? comment : StringFormat("SQ ticket: %d", sqTicket++);
- mrequest.expiration = expiration;
- //--- send order
- OrderSend(mrequest,mresult);
- // get the result code
- if(mresult.retcode==10009 || mresult.retcode==10008) //Request is completed or order placed
- {
- Alert("The order has been successfully placed with Ticket#:",mresult.order,"!!");
- return mresult.order;
- }
- else
- {
- Alert("The order request could not be completed. Error no.: ", GetLastError());
- Alert("Error description: " + ErrorDescription(GetLastError()));
- ResetLastError();
- return 0;
- }
- }
- //+------------------------------------------------------------------+
- /*
- int sqOpenOrder(int orderType, string symbol, double size, double price, double stopLoss, double profitTarget, int magicNumber, string comment, datetime expirationInTime, bool replaceExisting, color arrowColor) {
- if(symbol == "NULL" || symbol == "Current") {
- symbol = Symbol();
- }
- // check if live order exists
- if(sqSelectOrder(magicNumber, symbol, sqGetDirectionFromOrderType(orderType), comment)) {
- Verbose("Order with these parameters already exists, cannot open another one!");
- Verbose("----------------------------------");
- return(0);
- }
- // check if pending order exists
- if(sqSelectPendingOrderByType(magicNumber, symbol, 0, comment)) {
- if(!replaceExisting) {
- Verbose("Pending Order with these parameters already exists, and replace is not allowed!", " ----------------");
- return(0);
- }
- // close pending order
- Verbose("Deleting previous pending order");
- sqDeletePendingOrder(OrderGetInteger(ORDER_TICKET));
- } else {
- Log("Existing order doesnt exist");
- }
- int ticket = 0;
- if(sqSupportECNBrokers) {
- ticket = sqOpenOrderImpl(orderType, symbol, size, price, 0, 0, magicNumber, comment, expirationInTime, arrowColor);
- } else {
- ticket = sqOpenOrderImpl(orderType, symbol, size, price, stopLoss, profitTarget, magicNumber, comment, expirationInTime, arrowColor);
- }
- if(ticket > 0) {
- if(sqSupportECNBrokers && (stopLoss != 0 || profitTarget != 0)) {
- if(!OrderSelect(ticket)) {
- Verbose("Cannot select order with ticket: ",ticket);
- }
- bool result = sqOrderModify(ticket, OrderGetDouble(ORDER_PRICE_OPEN), stopLoss, profitTarget);
- if(!result) {
- Verbose("Cannot set SL / PT for this order, deleting it!");
- OrderDelete(ticket);
- }
- }
- }
- // reset global variables for this order
- sqSetOrderExpiration(ticket, 0);
- sqSetExitAfterXBars(ticket, 0);
- sqSetMoveSL2BE(ticket, 0, 0);
- sqSetSL2BEAddPips(ticket, 0);
- sqSetTrailingStop(ticket, 0, 0);
- sqSetTSActivation(ticket, 0);
- return(ticket);
- }
- //+------------------------------------------------------------------+
- int sqOpenOrderImpl(int orderType, string symbol, double size, double price, double stopLoss, double profitTarget, int magicNumber, string comment, datetime expiration, color arrowColor) {
- int ticket = 0;
- Verbose("Opening order with MagicNumber: ", magicNumber,", type: ", sqGetOrderTypeAsString(orderType), ", size: ", size, ", price: ", price, ", SL: ", stopLoss, ", PT: ", profitTarget, ", comment: ", comment);
- Verbose("Current Ask: ", SymbolInfoDouble(symbol, SYMBOL_ASK), ", Bid: ", SymbolInfoDouble(symbol, SYMBOL_BID));
- if(!sqCheckConnected()) {
- return(-1);
- }
- int digits = SymbolInfoInteger(symbol, SYMBOL_DIGITS);
- GetLastError(); // clear the global variable.
- int error = 0;
- int retries = 0;
- bool result;
- while (true) {
- if (IsTradeAllowed()) {
- if(orderType == ORDER_TYPE_BUY || orderType == ORDER_TYPE_SELL) {
- // get newest Ask/Bid price for market order
- RefreshRates();
- if(orderType == ORDER_TYPE_BUY) {
- price = sqGetAsk(symbol);
- } else {
- price = sqGetBid(symbol);
- }
- }
- if (digits > 0) price = NormalizeDouble(price, digits);
- ticket = openPosition((ENUM_ORDER_TYPE) orderType, symbol, size, price, stopLoss, profitTarget, sqMaxSlippage, comment, magicNumber, expiration);
- //ticket = OrderSend(symbol, orderType, size, price, sqMaxSlippage, stopLoss, profitTarget, comment, magicNumber, expiration, arrowColor);
- if(ticket > 0) {
- Verbose("Order placed cuccessfuly,ticket: ", ticket);
- return(ticket);
- }
- }
- retries++;
- if(!sqProcessErrors(retries, GetLastError())) {
- return(-1);
- }
- }
- Verbose("Retries of opening order finished", " ----------------");
- return(-1);
- }
- */
- //+------------------------------------------------------------------+
- void closeAllPositions(){
- for (int i=PositionsTotal() - 1; i >= 0; i--) {
- ulong ticket = PositionGetTicket(i);
- PositionSelectByTicket(ticket);
- if(sqClosePositionAtMarket(ticket)){
- Print(StringFormat("Cannot close position with ticket %d", ticket));
- }
- }
- }
- //+------------------------------------------------------------------+
- bool closePosition(const ulong ticket, const ulong deviation = 100, const string comment = "", const int magicNo = -1) {
- ZeroMemory(mrequest);
- if(!PositionSelectByTicket(ticket)) return(false);
- string symbol = PositionGetString(POSITION_SYMBOL);
- if((ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) {
- //--- prepare request for close BUY position
- mrequest.type = ORDER_TYPE_SELL;
- mrequest.price = NormalizeDouble(latest_price.bid, _Digits);
- }
- else {
- //--- prepare request for close SELL position
- mrequest.type = ORDER_TYPE_BUY;
- mrequest.price = NormalizeDouble(latest_price.ask, _Digits);
- }
- //--- setting request
- mrequest.action = TRADE_ACTION_DEAL;
- mrequest.position = ticket;
- mrequest.symbol = symbol;
- mrequest.volume = PositionGetDouble(POSITION_VOLUME);
- mrequest.magic = magicNo > 0 ? magicNo : magicNumber;
- mrequest.deviation = deviation;
- mrequest.comment = StringLen(comment) > 0 ? comment : PositionGetString(POSITION_COMMENT);
- //--- close position
- OrderSend(mrequest, mresult);
- // get the result code
- if(mresult.retcode==10009 || mresult.retcode==10008) //Request is completed or order placed
- {
- Alert("A Buy order has been successfully placed with Ticket#:",mresult.order,"!!");
- return true;
- }
- else
- {
- Alert("The Buy order request could not be completed -error:",GetLastError());
- ResetLastError();
- return false;
- }
- }
- //+------------------------------------------------------------------+
- bool OrderModify(int ticket, double stopLoss, double profitTarget){
- ZeroMemory(mrequest);
- PositionSelectByTicket(ticket);
- //--- setting request
- mrequest.action = TRADE_ACTION_SLTP;
- mrequest.symbol = PositionGetString(POSITION_SYMBOL);
- mrequest.magic = PositionGetInteger(POSITION_MAGIC);
- mrequest.position = ticket;
- mrequest.sl = stopLoss != 0 ? stopLoss : PositionGetDouble(POSITION_SL);
- mrequest.tp = profitTarget != 0 ? profitTarget : PositionGetDouble(POSITION_TP);
- //--- action and return the result
- return(OrderSend(mrequest,mresult));
- }
- //+------------------------------------------------------------------+
- /*
- bool sqOrderModifySL(int ticket,double stopLoss, int type) {
- if(!OrderSelect(ticket)) {
- Verbose("Cannot select order with ticket: ",ticket);
- }
- double orderOpenPrice = OrderGetDouble(ORDER_PRICE_OPEN);
- if(type == SLPTTYPE_RANGE) {
- // convert range to price level
- if(sqGetDirectionFromOrderType(OrderGetInteger(ORDER_TYPE)) == 1) {
- // it is long order
- stopLoss = orderOpenPrice - stopLoss;
- } else {
- stopLoss = orderOpenPrice + stopLoss;
- }
- }
- return(sqOrderModify(ticket, orderOpenPrice, stopLoss, OrderGetDouble(ORDER_TP)));
- }
- //+------------------------------------------------------------------+
- bool sqOrderModifyPT(int ticket,double profitTarget, int type) {
- if(!OrderSelect(ticket)) {
- Verbose("Cannot select order with ticket: ",ticket);
- }
- ENUM_ORDER_TYPE orderType = OrderGetInteger(ORDER_TYPE);
- double orderOpenPrice = OrderGetDouble(ORDER_PRICE_OPEN);
- double orderStopLoss = OrderGetDouble(ORDER_SL);
- if(type == SLPTTYPE_RANGE) {
- // convert range to price level
- if(sqGetDirectionFromOrderType(orderType) == 1) {
- // it is long order
- profitTarget = orderOpenPrice + profitTarget;
- } else {
- profitTarget = orderOpenPrice - profitTarget;
- }
- }
- return(sqOrderModify(ticket, orderOpenPrice, orderStopLoss, profitTarget));
- }
- //+------------------------------------------------------------------+
- bool sqOrderModify(int ticket, double price, double stopLoss, double profitTarget) {
- if(!OrderSelect(ticket)) {
- Verbose("Cannot select order with ticket: ",ticket);
- }
- int digits = SymbolInfoInteger(OrderGetString(ORDER_SYMBOL), SYMBOL_DIGITS);
- if (digits > 0) {
- stopLoss = NormalizeDouble(stopLoss, digits);
- profitTarget = NormalizeDouble(profitTarget, digits);
- }
- Verbose("Modifying order with ticket: ", ticket, ", SL: ", stopLoss, " and PT: ", profitTarget);
- int orderType = OrderGetInteger(ORDER_TYPE);
- if(!sqCheckConnected()) {
- return(false);
- }
- GetLastError(); // clear the global variable.
- int error = 0;
- int retries = 0;
- bool result;
- while (true) {
- if (IsTradeAllowed()) {
- result = OrderModify(ticket, price, stopLoss, profitTarget, OrderGetInteger(ORDER_TIME_EXPIRATION));
- if(result) {
- Verbose("Order modified successfuly");
- return(true);
- }
- }
- retries++;
- if(!sqProcessErrors(retries, GetLastError())) {
- return(false);
- }
- }
- }
- */
- //+------------------------------------------------------------------+
- ENUM_ORDER_TYPE_FILLING GetFilling( const string Symb, const uint Type = ORDER_FILLING_FOK ) {
- const ENUM_SYMBOL_TRADE_EXECUTION ExeMode = (ENUM_SYMBOL_TRADE_EXECUTION)::SymbolInfoInteger(Symb, SYMBOL_TRADE_EXEMODE);
- const int FillingMode = (int)::SymbolInfoInteger(Symb, SYMBOL_FILLING_MODE);
- if(FillingMode == 0 || (Type >= ORDER_FILLING_RETURN) || ((FillingMode & (Type + 1)) != Type + 1)) {
- if((ExeMode == SYMBOL_TRADE_EXECUTION_EXCHANGE) || (ExeMode == SYMBOL_TRADE_EXECUTION_INSTANT)) {
- return ORDER_FILLING_RETURN;
- }
- else {
- if(FillingMode == SYMBOL_FILLING_IOC) {
- return ORDER_FILLING_IOC;
- }
- else {
- return ORDER_FILLING_FOK;
- }
- }
- }
- else {
- return Type;
- }
- }
- //+------------------------------------------------------------------+
- double getDealCurrentProfit(long dealTicket) {
- long orderTicket = HistoryDealGetInteger(dealTicket, DEAL_ORDER);
- return getOrderCurrentProfit(orderTicket);
- }
- //+------------------------------------------------------------------+
- double getDealCurrentPriceDifference(long dealTicket){
- long orderTicket = HistoryDealGetInteger(dealTicket, DEAL_ORDER);
- return getOrderCurrentPriceDifference(orderTicket);
- }
- //+------------------------------------------------------------------+
- double getOrderCurrentProfit(long orderTicket){
- if(!OrderSelect(orderTicket)) return(0);
- ENUM_ORDER_TYPE orderType = OrderGetInteger(ORDER_TYPE);
- string orderSymbol = OrderGetString(ORDER_SYMBOL);
- double orderVolume = OrderGetDouble(ORDER_VOLUME_INITIAL);
- double orderOpenPrice = OrderGetDouble(ORDER_PRICE_OPEN);
- double orderCurrentPrice = OrderGetDouble(ORDER_PRICE_CURRENT);
- double profit = 0;
- OrderCalcProfit(orderType, orderSymbol, orderVolume, orderOpenPrice, orderCurrentPrice, profit);
- return profit;
- }
- //+------------------------------------------------------------------+
- double getOrderCurrentPriceDifference(long orderTicket){
- if(!OrderSelect(orderTicket)) return(0);
- ENUM_ORDER_TYPE orderType = OrderGetInteger(ORDER_TYPE);
- double orderOpenPrice = OrderGetDouble(ORDER_PRICE_OPEN);
- double orderCurrentPrice = OrderGetDouble(ORDER_PRICE_CURRENT);
- return orderType == ORDER_TYPE_BUY ? orderCurrentPrice - orderOpenPrice : orderOpenPrice - orderCurrentPrice;
- }
- //+------------------------------------------------------------------+
- //| old SQ.mqh functions |
- //+------------------------------------------------------------------+
- double iOpen(string symbol,int tf,int index){
- if(index < 0) return(-1);
- double Arr[];
- ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
- if(CopyOpen(correctSymbol(symbol),timeframe, index, 1, Arr)>0)
- return(Arr[0]);
- else return(-1);
- }
- //+------------------------------------------------------------------+
- double iHigh(string symbol,int tf,int index){
- if(index < 0) return(-1);
- double Arr[];
- ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
- if(CopyHigh(correctSymbol(symbol),timeframe, index, 1, Arr)>0)
- return(Arr[0]);
- else return(-1);
- }
- //+------------------------------------------------------------------+
- double iLow(string symbol,int tf,int index)
- {
- if(index < 0) return(-1);
- double Arr[];
- ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
- if(CopyLow(correctSymbol(symbol),timeframe, index, 1, Arr)>0)
- return(Arr[0]);
- else return(-1);
- }
- //+------------------------------------------------------------------+
- double iClose(string symbol,int tf,int index){
- if(index < 0) return(-1);
- double Arr[];
- ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
- if(CopyClose(correctSymbol(symbol),timeframe, index, 1, Arr)>0)
- return(Arr[0]);
- else return(-1);
- }
- //+------------------------------------------------------------------+
- datetime iTime(string symbol,int tf,int index)
- {
- if(index < 0) return(-1);
- ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
- datetime Arr[];
- if(CopyTime(correctSymbol(symbol), timeframe, index, 1, Arr)>0)
- return(Arr[0]);
- else return(-1);
- }
- //+------------------------------------------------------------------+
- double getOpen(int shift){
- return iOpen(_Symbol, _Period, shift);
- }
- //+------------------------------------------------------------------+
- double getHigh(int shift){
- return iHigh(_Symbol, _Period, shift);
- }
- //+------------------------------------------------------------------+
- double getLow(int shift){
- return iLow(_Symbol, _Period, shift);
- }
- //+------------------------------------------------------------------+
- double getClose(int shift){
- return iClose(_Symbol, _Period, shift);
- }
- //+------------------------------------------------------------------+
- double getTime(int shift){
- return iTime(_Symbol, _Period, shift);
- }
- //+------------------------------------------------------------------+
- int TimeHour(datetime date)
- {
- MqlDateTime tm;
- TimeToStruct(date,tm);
- return(tm.hour);
- }
- //+------------------------------------------------------------------+
- int TimeMinute(datetime date)
- {
- MqlDateTime tm;
- TimeToStruct(date,tm);
- return(tm.min);
- }
- //+------------------------------------------------------------------+
- ENUM_TIMEFRAMES TFMigrate(int tf)
- {
- switch(tf)
- {
- case 0: return(PERIOD_CURRENT);
- case 1: return(PERIOD_M1);
- case 5: return(PERIOD_M5);
- case 15: return(PERIOD_M15);
- case 30: return(PERIOD_M30);
- case 60: return(PERIOD_H1);
- case 240: return(PERIOD_H4);
- case 1440: return(PERIOD_D1);
- case 10080: return(PERIOD_W1);
- case 43200: return(PERIOD_MN1);
- case 2: return(PERIOD_M2);
- case 3: return(PERIOD_M3);
- case 4: return(PERIOD_M4);
- case 6: return(PERIOD_M6);
- case 10: return(PERIOD_M10);
- case 12: return(PERIOD_M12);
- case 16385: return(PERIOD_H1);
- case 16386: return(PERIOD_H2);
- case 16387: return(PERIOD_H3);
- case 16388: return(PERIOD_H4);
- case 16390: return(PERIOD_H6);
- case 16392: return(PERIOD_H8);
- case 16396: return(PERIOD_H12);
- case 16408: return(PERIOD_D1);
- case 32769: return(PERIOD_W1);
- case 49153: return(PERIOD_MN1);
- default: return(PERIOD_CURRENT);
- }
- }
- //+------------------------------------------------------------------+
- void sqCloseWorstPosition(string symbol, int magicNo, int direction, string comment) {
- double minPL = 100000000;
- ulong ticket = 0;
- for(int cc = PositionsTotal() - 1; cc >= 0; cc--) {
- ulong positionTicket = PositionGetTicket(cc);
- if(PositionSelect(positionTicket)) {
- double positionProfit = PositionGetDouble(POSITION_PROFIT);
- if(positionProfit < minPL) {
- // found order with worse profit
- minPL = positionProfit;
- ticket = positionTicket;
- Verbose("Worse position found, ticket: ", ticket,", PL: ", minPL);
- }
- }
- }
- if(ticket > 0) {
- sqClosePositionAtMarket(ticket);
- }
- }
- //+------------------------------------------------------------------+
- /*
- void sqManageTrailingStop(int positionTicket) {
- double tempValue = 0;
- double tempValue2 = 0;
- double plValue = 0;
- double newSL = 0;
- int error;
- // Trailing Stop
- tempValue = sqGetPositionTrailingStop(positionTicket, PositionGetInteger(POSITION_TYPE));
- if(tempValue > 0) {
- tempValue2 = sqGetPositionTSActivation(positionTicket);
- string positionSymbol = PositionGetString(POSITION_SYMBOL);
- double positionOpenPrice = PositionGetDouble(POSITION_PRICE_OPEN);
- double positionStopLoss = PositionGetDouble(POSITION_SL);
- double positionProfitTarget = PositionGetDouble(POSITION_TP);
- if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) {
- plValue = sqGetBid(positionSymbol) - positionOpenPrice;
- newSL = tempValue;
- if (plValue >= tempValue2 && (positionStopLoss == 0 || positionStopLoss < newSL) && !sqDoublesAreEqual(positionStopLoss, newSL)) {
- Verbose("Moving trailing stop for order with ticket: ", positionTicket, " to :", newSL);
- if(!OrderModify(positionTicket, newSL, positionProfitTarget)) {
- error = GetLastError();
- Verbose("Failed, error: ", error, " - ", ErrorDescription(error));
- }
- }
- } else { // POSITION_TYPE_SELL
- plValue = positionOpenPrice - sqGetAsk(positionSymbol);
- newSL = tempValue;
- if (plValue >= tempValue2 && (positionStopLoss == 0 || positionStopLoss > newSL) && !sqDoublesAreEqual(positionStopLoss, newSL)) {
- Verbose("Moving trailing stop for order with ticket: ", positionTicket, " to :", newSL);
- if(!OrderModify(positionTicket, newSL, positionProfitTarget)) {
- error = GetLastError();
- Verbose("Failed, error: ", error, " - ", ErrorDescription(error),", Ask: ", sqGetAsk(positionSymbol), ", Bid: ", sqGetBid(positionSymbol), " Current SL: ", positionStopLoss);
- }
- }
- }
- }
- }
- */
- //+------------------------------------------------------------------+
- void sqManageExitAfterXBars(ulong positionTicket) {
- int exitBars = sqGetExitAfterXBars(positionTicket);
- if(exitBars > 0) {
- datetime openTime = PositionGetInteger(POSITION_TIME);
- if(sqGetOpenBarsForOrder(exitBars+10, openTime) >= exitBars) {
- Verbose("Exit After ", exitBars, "bars - closing order with ticket: ", positionTicket);
- sqClosePositionAtMarket(positionTicket);
- }
- }
- }
- //+------------------------------------------------------------------+
- /*
- void sqManageSL2BE(ulong positionTicket) {
- double tempValue = 0;
- double tempValue2 = 0;
- double newSL = 0;
- int error;
- int positionType = PositionGetInteger(POSITION_TYPE);
- string positionSymbol = PositionGetString(POSITION_SYMBOL);
- double positionOpenPrice = PositionGetDouble(POSITION_PRICE_OPEN);
- double positionStopLoss = PositionGetDouble(POSITION_SL);
- double positionProfitTarget = PositionGetDouble(POSITION_TP);
- // Move Stop Loss to Break Even
- tempValue = sqGetOrderBreakEven(positionTicket, positionType);
- tempValue2 = sqGetBreakEvenAddPips(positionTicket);
- if(tempValue > 0) {
- if(positionType == POSITION_TYPE_BUY) {
- newSL = positionOpenPrice + tempValue2;
- if (positionOpenPrice <= tempValue && (positionStopLoss == 0 || positionStopLoss < newSL) && !sqDoublesAreEqual(positionStopLoss, newSL)) {
- Verbose("Moving SL 2 BE for order with ticket: ", positionTicket, " to :", newSL);
- if(!OrderModify(positionTicket, newSL, positionProfitTarget)) {
- error = GetLastError();
- Verbose("Failed, error: ", error, " - ", ErrorDescription(error),", Ask: ", sqGetAsk(positionSymbol), ", Bid: ", sqGetBid(positionSymbol), " Current SL: ", positionStopLoss);
- }
- }
- } else {
- newSL = positionOpenPrice - tempValue2;
- if (positionOpenPrice >= tempValue && (positionStopLoss == 0 || positionStopLoss > newSL) && !sqDoublesAreEqual(positionStopLoss, newSL)) {
- Verbose("Moving SL 2 BE for order with ticket: ", positionTicket, " to :", newSL);
- if(!OrderModify(positionTicket, newSL, positionProfitTarget)) {
- error = GetLastError();
- Verbose("Failed, error: ", error, " - ", ErrorDescription(error),", Ask: ", sqGetAsk(positionSymbol), ", Bid: ", sqGetBid(positionSymbol), " Current SL: ", positionStopLoss);
- }
- }
- }
- }
- }
- */
- //+------------------------------------------------------------------+
- bool sqClosePositionAtMarket(ulong positionTicket) {
- Verbose("Closing order with ticket: ", positionTicket);
- ENUM_POSITION_TYPE positionType = PositionGetInteger(POSITION_TYPE);
- string positionSymbol = PositionGetString(POSITION_SYMBOL);
- if(!sqCheckConnected()) {
- return(-1);
- }
- GetLastError(); // clear the global variable.
- int error = 0;
- int retries = 0;
- bool result;
- while (true) {
- if (IsTradeAllowed()) {
- double price;
- if(positionType == POSITION_TYPE_BUY) {
- price = sqGetBid(positionSymbol);
- } else {
- price = sqGetAsk(positionSymbol);
- }
- result = closePosition(positionTicket, sqMaxSlippage);
- if(result) {
- Verbose("Order deleted successfuly");
- return(true);
- }
- }
- if(!sqProcessErrors(retries, GetLastError())) {
- return(-1);
- }
- }
- }
- //+------------------------------------------------------------------+
- bool IsTradeAllowed(){
- return terminalInfo.IsTradeAllowed();
- }
- //+------------------------------------------------------------------+
- bool sqCheckConnected() {
- if (!terminalInfo.IsConnected()) {
- Verbose("Not connected!");
- return(false);
- }
- if (IsStopped()) {
- Verbose("EA stopped!");
- return(false);
- }
- return(true);
- }
- //+------------------------------------------------------------------+
- double sqGetAsk(string symbol) {
- symbol = correctSymbol(symbol);
- return(NormalizeDouble(SymbolInfoDouble(symbol, SYMBOL_ASK), _Digits));
- }
- //+------------------------------------------------------------------+
- double sqGetBid(string symbol) {
- symbol = correctSymbol(symbol);
- return(NormalizeDouble(SymbolInfoDouble(symbol, SYMBOL_BID), _Digits));
- }
- //+------------------------------------------------------------------+
- bool sqProcessErrors(int retries, int error) {
- if (retries > sqMaxRetries) {
- Verbose("Maximum retries ", sqMaxRetries, " reached. Error: ", error, " : " + ErrorDescription(error));
- return(false);
- }
- if(error == TRADE_RETCODE_PRICE_CHANGED || error == TRADE_RETCODE_REQUOTE) {
- // continue immediately
- return(true);
- } else if(error == TRADE_RETCODE_CONNECTION || error == TRADE_RETCODE_INVALID_PRICE || error == TRADE_RETCODE_TIMEOUT
- /*error == ERR_OFF_QUOTES || error == ERR_BROKER_BUSY || error == ERR_TRADE_CONTEXT_BUSY*/)
- {
- Verbose("Retrying #", retries,", Error: ", error, " : " + ErrorDescription(error));
- sqSleep();
- return(true);
- } else {
- // too serious error
- Verbose("Non-retriable error. Error: ", error, " : " + ErrorDescription(error));
- return(false);
- }
- }
- //+------------------------------------------------------------------+
- void sqManageOrderExpirations() {
- int tempValue = 0;
- int barsOpen = 0;
- for (int i = OrdersTotal() - 1; i >= 0; i--) {
- ulong orderTicket = OrderGetTicket(i);
- if(!OrderSelect(orderTicket)) continue;
- ENUM_ORDER_TYPE orderType = OrderGetInteger(ORDER_TYPE);
- datetime openTime = OrderGetInteger(ORDER_TIME_SETUP);
- // Stop/Limit Order Expiration
- if(orderType != ORDER_TYPE_BUY && orderType != ORDER_TYPE_SELL) {
- // handle only pending orders
- tempValue = sqGetOrderExpiration(orderTicket);
- if(tempValue > 0) {
- barsOpen = sqGetOpenBarsForOrder(tempValue + 10, openTime);
- if(barsOpen >= tempValue) {
- Verbose("Order with ticket: ", orderTicket, " expired");
- sqDeletePendingOrder(orderTicket);
- }
- }
- }
- }
- }
- //----------------------------------------------------------------------------
- double sqIndicatorHighest(int period, int nthValue, string indicatorIdentification) {
- double indicatorValues[200];
- int i;
- for(i=0; i<200; i++) {
- indicatorValues[i] = -2147483647;
- }
- for(i=0; i<period; i++) {
- indicatorValues[i] = sqGetIndicatorValue(indicatorIdentification, i);
- }
- ArraySort(indicatorValues); //ascending order
- int index = period - nthValue;
- if(index < 0 || index >= period) {
- return(-1);
- }
- return(indicatorValues[index]);
- }
- //----------------------------------------------------------------------------
- double sqIndicatorLowest(int period, int nthValue, string indicatorIdentification) {
- double indicatorValues[200];
- int i;
- for(i=0; i<200; i++) {
- indicatorValues[i] = 2147483647;
- }
- for(i=0; i<period; i++) {
- indicatorValues[i] = sqGetIndicatorValue(indicatorIdentification, i);
- }
- ArraySort(indicatorValues);
- if(nthValue < 0 || nthValue >= period) {
- return(-1);
- }
- return(indicatorValues[nthValue]);
- }
- //----------------------------------------------------------------------------
- double sqIndicatorAverage(int period, int maMethod, string indicatorIdentification) {
- double indicatorValues[10000];
- for(int i=0; i<period; i++) {
- indicatorValues[i] = sqGetIndicatorValue(indicatorIdentification, i);
- }
- double maValue = iMAOnArray(indicatorValues, period, period, 0, maMethod, 0);
- return(maValue);
- }
- double iMAOnArray(double &array[], int total, int period, int ma_shift, int ma_method, int shift) {
- double buf[],arr[];
- if(total==0) total=ArraySize(array);
- if(total>0 && total<=period) return(0);
- if(shift>total-period-ma_shift) return(0);
- switch(ma_method)
- {
- case MODE_SMA :
- {
- total=ArrayCopy(arr,array,0,shift+ma_shift,period);
- if(ArrayResize(buf,total)<0) return(0);
- double sum=0;
- int i,pos=total-1;
- for(i=1;i<period;i++,pos--)
- sum+=arr[pos];
- while(pos>=0)
- {
- sum+=arr[pos];
- buf[pos]=sum/period;
- sum-=arr[pos+period-1];
- pos--;
- }
- return(buf[0]);
- }
- case MODE_EMA :
- {
- if(ArrayResize(buf,total)<0) return(0);
- double pr=2.0/(period+1);
- int pos=total-2;
- while(pos>=0)
- {
- if(pos==total-2) buf[pos+1]=array[pos+1];
- buf[pos]=array[pos]*pr+buf[pos+1]*(1-pr);
- pos--;
- }
- return(buf[shift+ma_shift]);
- }
- case MODE_SMMA :
- {
- if(ArrayResize(buf,total)<0) return(0);
- double sum=0;
- int i,k,pos;
- pos=total-period;
- while(pos>=0)
- {
- if(pos==total-period)
- {
- for(i=0,k=pos;i<period;i++,k++)
- {
- sum+=array[k];
- buf[k]=0;
- }
- }
- else sum=buf[pos+1]*(period-1)+array[pos];
- buf[pos]=sum/period;
- pos--;
- }
- return(buf[shift+ma_shift]);
- }
- case MODE_LWMA :
- {
- if(ArrayResize(buf,total)<0) return(0);
- double sum=0.0,lsum=0.0;
- double price;
- int i,weight=0,pos=total-1;
- for(i=1;i<=period;i++,pos--)
- {
- price=array[pos];
- sum+=price*i;
- lsum+=price;
- weight+=i;
- }
- pos++;
- i=pos+period;
- while(pos>=0)
- {
- buf[pos]=sum/weight;
- if(pos==0) break;
- pos--;
- i--;
- price=array[pos];
- sum=sum-lsum+price*period;
- lsum-=array[i];
- lsum+=price;
- }
- return(buf[shift+ma_shift]);
- }
- default: return(0);
- }
- return(0);
- }
- //----------------------------------------------------------------------------
- double sqIndicatorRecent(int barsBack, string indicatorIdentification) {
- return(sqGetIndicatorValue(indicatorIdentification, barsBack));
- }
- //+------------------------------------------------------------------+
- int sqGetOrderExpiration(int ticket) {
- return (GlobalVariableGet("sqOrderExpiration_"+ticket));
- }
- //+------------------------------------------------------------------+
- void sqSetOrderExpiration(int ticket, int bars) {
- GlobalVariableSet("sqOrderExpiration_"+ticket, bars);
- }
- //+------------------------------------------------------------------+
- int sqGetExitAfterXBars(int ticket) {
- return (GlobalVariableGet("sqExitAfterXBars_"+ticket));
- }
- //+------------------------------------------------------------------+
- void sqSetExitAfterXBars(int ticket, int bars) {
- GlobalVariableSet("sqExitAfterXBars_"+ticket, bars);
- }
- //+------------------------------------------------------------------+
- int sqGetMoveSL2BE(int ticket) {
- return (GlobalVariableGet("sqMoveSL2BE_"+ticket));
- }
- //+------------------------------------------------------------------+
- int sqGetMoveSL2BEType(int ticket) {
- return (GlobalVariableGet("sqMoveSL2BEType_"+ticket));
- }
- //+------------------------------------------------------------------+
- void sqSetMoveSL2BE(int ticket, string value, int type) {
- GlobalVariableSet("sqMoveSL2BE_"+ticket, sqStringHash(value));
- GlobalVariableSet("sqMoveSL2BEType_"+ticket, type);
- }
- //+------------------------------------------------------------------+
- int sqGetSL2BEAddPips(int ticket) {
- return (GlobalVariableGet("sqSL2BEAddPips_"+ticket));
- }
- //+------------------------------------------------------------------+
- void sqSetSL2BEAddPips(int ticket, string value) {
- GlobalVariableSet("sqSL2BEAddPips_"+ticket, sqStringHash(value));
- }
- //+------------------------------------------------------------------+
- int sqGetTrailingStop(int ticket) {
- return (GlobalVariableGet("sqTrailingStop"+ticket));
- }
- //+------------------------------------------------------------------+
- int sqGetTrailingStopType(int ticket) {
- return (GlobalVariableGet("sqTrailingStopType"+ticket));
- }
- //+------------------------------------------------------------------+
- void sqSetTrailingStop(int ticket, string value, int type) {
- GlobalVariableSet("sqTrailingStop"+ticket, sqStringHash(value));
- GlobalVariableSet("sqTrailingStopType"+ticket, type);
- }
- //+------------------------------------------------------------------+
- int sqGetTSActivation(int positionTicket) {
- return (GlobalVariableGet("sqTSActivation"+positionTicket));
- }
- //+------------------------------------------------------------------+
- void sqSetTSActivation(int ticket, string value) {
- GlobalVariableSet("sqTSActivation"+ticket, sqStringHash(value));
- }
- //+------------------------------------------------------------------+
- int sqStringHash(string str){
- int i, h = 0, k = 0;
- for (i=0; i<StringLen(str); i++){
- k = StringGetCharacter(str, i);
- h = (h << 5) + h + k;
- }
- return(h);
- }
- //+------------------------------------------------------------------+
- void sqClosePosition(double size, int magicNumber, string symbol, int direction, string comment) {
- Verbose("Closing order with Magic Number: ", magicNumber, ", symbol: ", symbol, ", direction: ", direction, ", comment: ", comment);
- if(!sqSelectPosition(magicNumber, symbol, direction, comment)) {
- Verbose("Position cannot be found");
- } else {
- ENUM_POSITION_TYPE positionType = PositionGetInteger(POSITION_TYPE);
- if(positionType == POSITION_TYPE_BUY || positionType == POSITION_TYPE_SELL) {
- sqClosePositionAtMarket(size);
- } else {
- //sqDeletePendingOrder(OrderTicket());
- }
- }
- Verbose("Closing order finished ----------------");
- }
- //+------------------------------------------------------------------+
- int sqGetOpenBarsForOrder(int expBarsPeriod, datetime openTime) {
- datetime Time[];
- int length = CopyTime(_Symbol, _Period, 0, expBarsPeriod+10, Time);
- if(length <= 0) return 0;
- ArrayGetAsSeries(Time);
- int numberOfBars = 0;
- for(int i=0; i<length; i++) {
- if(openTime < Time[i]) {
- numberOfBars++;
- }
- }
- return(numberOfBars);
- }
- //+------------------------------------------------------------------+
- void Verbose(string st1, string st2="", string s3="", string s4="", string s5="", string s6="", string s7="", string s8="", string s9="", string s10="", string s11="", string s12="", string s13="", string s14="" ) {
- if(sqVerboseMode == 1) {
- // log to standard log
- Print("---VERBOSE--- ", TimeToString(TimeCurrent()), " ", st1, st2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14);
- } else if(sqVerboseMode == 2) {
- // log to special file
- int handle = FileOpen("EAW_VerboseLog.txt", FILE_READ | FILE_WRITE);
- if(handle>0) {
- FileSeek(handle,0,SEEK_END);
- FileWrite(handle, TimeToString(TimeCurrent()), " VERBOSE: ", st1, st2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12);
- FileClose(handle);
- }
- }
- }
- //+------------------------------------------------------------------+
- void VerboseLog(string s1, string s2="", string s3="", string s4="", string s5="", string s6="", string s7="", string s8="", string s9="", string s10="", string s11="", string s12="" ) {
- if(sqVerboseMode != 1) {
- Log(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12);
- }
- Verbose(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12);
- }
- //+------------------------------------------------------------------+
- 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(TimeToString(TimeCurrent()), " ", s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12);
- }
- //+------------------------------------------------------------------+
- void sqLog(string st1, string st2="", string s3="", string s4="", string s5="", string s6="", string s7="", string s8="", string s9="", string s10="", string s11="", string s12="" ) {
- Print(TimeToString(TimeCurrent()), " ", st1, st2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12);
- }
- //+------------------------------------------------------------------+
- void sqLogToFile(string fileName, string st1, string st2="", string s3="", string s4="", string s5="", string s6="", string s7="", string s8="", string s9="", string s10="", string s11="", string s12="" ) {
- int handle = FileOpen(fileName, FILE_READ | FILE_WRITE, ";");
- if(handle>0) {
- FileSeek(handle,0,SEEK_END);
- FileWrite(handle, TimeToString(TimeCurrent()), " ", st1, st2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12);
- FileClose(handle);
- }
- }
- //+------------------------------------------------------------------+
- bool sqSelectPosition(int magicNumber, string symbol, int direction, string comment) {
- for (int cc = PositionsTotal() - 1; cc >= 0; cc--) {
- ulong ticket = PositionGetTicket(cc);
- if (PositionSelectByTicket(ticket) && positionFits(ticket, symbol, magicNumber, direction, comment)) {
- return(true);
- }
- }
- return(false);
- }
- //+------------------------------------------------------------------+
- bool sqSelectOrder(int magicNumber, string symbol, int direction, string comment) {
- for (int cc = OrdersTotal() - 1; cc >= 0; cc--) {
- ulong ticket = OrderGetTicket(cc);
- if (OrderSelect(ticket) && orderFits(ticket, symbol, magicNumber, direction, comment)) {
- return(true);
- }
- }
- return(false);
- }
- //+------------------------------------------------------------------+
- bool positionFits(ulong ticket, string symbol, int magicNumber, int direction, string comment){
- ENUM_POSITION_TYPE positionType = PositionGetInteger(POSITION_TYPE);
- string positionSymbol = PositionGetString(POSITION_SYMBOL);
- string positionComment = PositionGetString(POSITION_COMMENT);
- int positionMagicNumber = PositionGetInteger(POSITION_MAGIC);
- if(direction != 0) {
- if(direction > 0 && positionType != POSITION_TYPE_BUY) return(false);
- if(direction < 0 && positionType != POSITION_TYPE_SELL) return(false);
- }
- if(magicNumber != 0) {
- if(positionMagicNumber != magicNumber) return(false);
- }
- if(symbol != "Any") {
- if(symbol == "NULL" || symbol == "Current") {
- symbol = Symbol();
- }
- if(positionSymbol != symbol) return(false);
- }
- if(comment != "") {
- if(StringFind(positionComment, comment) == -1) return(false);
- }
- return(true);
- }
- //+------------------------------------------------------------------+
- bool dealFits(ulong ticket, string symbol, int magicNumber, int direction, string comment){
- ENUM_DEAL_TYPE dealType = HistoryDealGetInteger(ticket, DEAL_TYPE);
- string dealSymbol = HistoryDealGetString(ticket, DEAL_SYMBOL);
- string dealComment = HistoryDealGetString(ticket, DEAL_COMMENT);
- int dealMagicNumber = HistoryDealGetInteger(ticket, DEAL_MAGIC);
- if(direction != 0) {
- if(direction > 0 && dealType != DEAL_TYPE_BUY) return(false);
- if(direction < 0 && dealType != DEAL_TYPE_SELL) return(false);
- }
- if(magicNumber != 0) {
- if(dealMagicNumber != magicNumber) return(false);
- }
- if(symbol != "Any") {
- if(symbol == "NULL" || symbol == "Current") {
- symbol = Symbol();
- }
- if(dealSymbol != symbol) return(false);
- }
- if(comment != "") {
- if(StringFind(dealComment, comment) == -1) return(false);
- }
- return(true);
- }
- //+------------------------------------------------------------------+
- bool orderFits(ulong ticket, string symbol, int magicNumber, int direction, string comment){
- ENUM_ORDER_TYPE orderType = OrderGetInteger(ORDER_TYPE);
- string orderSymbol = OrderGetString(ORDER_SYMBOL);
- string orderComment = OrderGetString(ORDER_COMMENT);
- int orderMagicNumber = OrderGetInteger(ORDER_MAGIC);
- if(direction != 0) {
- if(direction > 0 && orderType != ORDER_TYPE_BUY) return(false);
- if(direction < 0 && orderType != ORDER_TYPE_SELL) return(false);
- }
- if(magicNumber != 0) {
- if(orderMagicNumber != magicNumber) return(false);
- }
- if(symbol != "Any") {
- if(symbol == "NULL" || symbol == "Current") {
- symbol = Symbol();
- }
- if(orderSymbol != symbol) return(false);
- }
- if(comment != "") {
- if(StringFind(orderComment, comment) == -1) return(false);
- }
- return(true);
- }
- //+------------------------------------------------------------------+
- void sqCloseAllPositions(string symbol, int magicNumber, int direction, string comment) {
- int count = 100; // maximum number of positions to close
- ulong lastTicket = -1;
- while(count > 0) {
- count--;
- if(!sqSelectPosition(magicNumber, symbol, direction, comment)) {
- // no position found
- break;
- }
- ulong positionTicket = PositionGetInteger(POSITION_TICKET);
- if(lastTicket == positionTicket) {
- // trying to close the same position one more time, there must be some error
- break;
- }
- lastTicket = positionTicket;
- sqClosePositionAtMarket(positionTicket);
- }
- }
- //+------------------------------------------------------------------+
- void sqCloseBestPosition(string symbol, int magicNumber, int direction, string comment) {
- double maxPL = -100000000;
- ulong ticket = 0;
- for (int cc = PositionsTotal() - 1; cc >= 0; cc--) {
- ulong positionTicket = PositionGetTicket(cc);
- if(PositionSelectByTicket(positionTicket) && positionFits(positionTicket, symbol, magicNumber, direction, comment)) {
- double positionProfit = PositionGetDouble(POSITION_PROFIT);
- if(positionProfit > maxPL) {
- // found order with better profit
- maxPL = positionProfit;
- ticket = positionTicket;
- Verbose("Better position found, ticket: ", positionTicket,", PL: ", maxPL);
- }
- }
- }
- if(ticket > 0) {
- PositionSelectByTicket(ticket);
- sqClosePositionAtMarket(ticket);
- }
- }
- //+------------------------------------------------------------------+
- int sqGetMarketPosition(string symbol, int magicNumber, string comment) {
- if(sqSelectPosition(magicNumber, symbol, 0, comment)) {
- ENUM_POSITION_TYPE positionType = PositionGetInteger(POSITION_TYPE);
- if(positionType == POSITION_TYPE_BUY) {
- return(1);
- } else {
- return(-1);
- }
- }
- /*
- //check pending orders
- if(sqSelectOrder(magicNumber, symbol, 0, comment)) {
- ENUM_ORDER_TYPE orderType = OrderGetInteger(ORDER_TYPE);
- if(orderType != ORDER_TYPE_BUY && orderType != ORDER_TYPE_SELL) {
- return(-1);
- }
- }
- */
- return(0);
- }
- //+------------------------------------------------------------------+
- double sqGetPositionOpenPrice(string symbol, int magicNumber, int direction, string comment) {
- if(sqSelectPosition(magicNumber, symbol, direction, comment)) {
- return(PositionGetDouble(POSITION_PRICE_OPEN));
- }
- return(-1);
- }
- //+------------------------------------------------------------------+
- double sqGetOrderStopLoss(string symbol, int magicNumber, int direction, string comment) {
- if(sqSelectPosition(magicNumber, symbol, direction, comment)) {
- return(PositionGetDouble(POSITION_SL));
- }
- return(-1);
- }
- //+------------------------------------------------------------------+
- double sqGetOrderProfitTarget(string symbol, int magicNumber, int direction, string comment) {
- if(sqSelectPosition(magicNumber, symbol, direction, comment)) {
- return(PositionGetDouble(POSITION_TP));
- }
- return(-1);
- }
- //+------------------------------------------------------------------+
- double sqGetMarketPositionSize(string symbol, int magicNumber, int direction, string comment) {
- double lots = 0;
- for (int cc = PositionsTotal() - 1; cc >= 0; cc--) {
- ulong positionTicket = PositionGetTicket(cc);
- if(PositionSelectByTicket(positionTicket) && positionFits(positionTicket, symbol, magicNumber, direction, comment)) {
- lots += PositionGetDouble(POSITION_VOLUME);
- }
- }
- return(lots);
- }
- //+------------------------------------------------------------------+
- double sqGetOpenPL(string symbol, int magicNumber, int direction, string comment) {
- double pl = 0;
- for (int cc = PositionsTotal() - 1; cc >= 0; cc--) {
- ulong positionTicket = PositionGetTicket(cc);
- if(PositionSelectByTicket(positionTicket) && positionFits(positionTicket, symbol, magicNumber, direction, comment)) {
- pl += PositionGetDouble(POSITION_PROFIT);
- }
- }
- return(pl);
- }
- //+------------------------------------------------------------------+
- double sqGetOpenPLInPips(string symbol, int magicNumber, int direction, string comment) {
- double priceDelta = 0;
- for (int cc = PositionsTotal() - 1; cc >= 0; cc--) {
- ulong positionTicket = PositionGetTicket(cc);
- if(PositionSelectByTicket(positionTicket) && positionFits(positionTicket, symbol, magicNumber, direction, comment)) {
- ENUM_POSITION_TYPE positionType = PositionGetInteger(POSITION_TYPE);
- double positionOpenPrice = PositionGetDouble(POSITION_PRICE_OPEN);
- double positionCurrentPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
- if(positionType == POSITION_TYPE_BUY){
- priceDelta += positionCurrentPrice - positionOpenPrice;
- }
- else {
- priceDelta += positionOpenPrice - positionCurrentPrice;
- }
- }
- }
- return(sqConvertToPips(symbol, priceDelta));
- }
- //+------------------------------------------------------------------+
- /*
- int sqGetClosedPLInPips(string symbol, int magicNumber, int direction, string comment, int shift) {
- int index = 0;
- HistorySelect(startTime, getTime(0));
- for(int i=HistoryDealsTotal(); i>=0; i--) {
- ulong ticket = HistoryDealGetTicket(i);
- if(dealFits(ticket, symbol, magicNumber, direction, comment)) {
- ENUM_DEAL_TYPE dealType = HistoryDealGetInteger(ticket, DEAL_TYPE);
- double profit = HistoryDealGetDouble(ticket, DEAL_PROFIT);
- if(index == shift) {
- if(dealType == DEAL_TYPE_BUY) {
- return(sqConvertToPips(correctSymbol(symbol), OrderClosePrice() - OrderOpenPrice()));
- } else {
- return(sqConvertToPips(correctSymbol(symbol), OrderOpenPrice() - OrderClosePrice()));
- }
- }
- index++;
- }
- }
- return(0);
- }
- //+------------------------------------------------------------------+
- double getDealPriceDelta(ulong ticket){
- double profit = HistoryDealGetDouble(ticket, DEAL_PROFIT);
- double volume = HistoryDealGetDouble(ticket, DEAL_VOLUME);
- string dealSymbol = HistoryDealGetString(ticket, DEAL_SYMBOL);
- double contractSize = SymbolInfoDouble(dealSymbol, SYMBOL_TRADE_CONTRACT_SIZE);
- double pointValue = SymbolInfoDouble(dealSymbol, SYMBOL_POINT);
- return profit * pointValue / contractSize;
- }
- */
- //+------------------------------------------------------------------+
- int sqGetClosedPLInMoney(string symbol, int magicNumber, int direction, string comment, int shift) {
- int index = 0;
- HistorySelect(startTime, getTime(0));
- for(int i=HistoryDealsTotal(); i>=0; i--) {
- ulong ticket = HistoryDealGetTicket(i);
- if(dealFits(ticket, symbol, magicNumber, direction, comment)) {
- if(index == shift) {
- return(HistoryDealGetDouble(ticket, DEAL_PROFIT));
- }
- index++;
- }
- }
- return(0);
- }
- //+------------------------------------------------------------------+
- int sqGetMarketPositionCount(string symbol, int magicNumber, int direction, string comment) {
- double count = 0;
- for (int cc = PositionsTotal() - 1; cc >= 0; cc--) {
- ulong positionTicket = PositionGetTicket(cc);
- if(PositionSelect(positionTicket) && positionFits(positionTicket, symbol, magicNumber, direction, comment)) {
- count++;
- }
- }
- return(count);
- }
- //+------------------------------------------------------------------+
- int sqGetBarsSinceOpen(string symbol, int magicNumber, int direction, string comment) {
- if(sqSelectPosition(magicNumber, symbol, direction, comment)) {
- datetime positionOpenTime = PositionGetInteger(POSITION_TIME);
- int numberOfBars = 0;
- datetime Time[];
- int length = CopyTime(_Symbol, _Period, 0, 10000, Time);
- if(length <= 0) return 0;
- ArrayGetAsSeries(Time);
- for(int i=0; i<10000; i++) {
- if(positionOpenTime < Time[i]) {
- numberOfBars++;
- }
- }
- return(numberOfBars);
- }
- return(-1);
- }
- //+------------------------------------------------------------------+
- int sqGetBarsSinceClose(string symbol, int magicNumber, int direction, string comment) {
- ulong ticket = sqSelectDeal(magicNumber, symbol, direction, comment);
- if(ticket > 0) {
- datetime clTime = HistoryDealGetInteger(ticket, DEAL_TIME);
- datetime Time[];
- int length = CopyTime(_Symbol, _Period, 0, 10000, Time);
- if(length <= 0) return 0;
- ArrayGetAsSeries(Time);
- int numberOfBars = 0;
- for(int i=0; i<10000; i++) {
- if(clTime < Time[i]) {
- numberOfBars++;
- }
- }
- return(numberOfBars);
- }
- return(-1);
- }
- //+------------------------------------------------------------------+
- int sqGetLastOrderType(string symbol, int magicNumber, string comment) {
- ulong ticket = sqSelectDeal(magicNumber, symbol, 0, comment);
- if(ticket > 0) {
- ENUM_DEAL_TYPE dealType = HistoryDealGetInteger(ticket, DEAL_TYPE);
- if(dealType == DEAL_TYPE_BUY) {
- return(1);
- } else {
- return(-1);
- }
- }
- return(0);
- }
- //+------------------------------------------------------------------+
- ulong sqSelectDeal(int magicNumber, string symbol, int direction, string comment) {
- HistorySelect(startTime, getTime(0));
- for(int i=HistoryDealsTotal() - 1; i>=0; i--) {
- ulong ticket = HistoryDealGetTicket(i);
- if (dealFits(ticket, symbol, magicNumber, direction, comment)) {
- return(ticket);
- }
- }
- return(0);
- }
- //+------------------------------------------------------------------+
- double sqConvertToPips(string symbol, double value) {
- if(symbol == "NULL" || symbol == "Current") {
- return(gPointPow * value);
- }
- // recognize point coeficient
- int realDigits = SymbolInfoInteger(symbol, SYMBOL_DIGITS);
- if(realDigits == 4 || realDigits == 5) {
- realDigits -= 1;
- }
- double pointPow = MathPow(10, realDigits);
- return(pointPow * value);
- }
- //+------------------------------------------------------------------+
- bool sqSelectPendingOrderByType(int magicNo, string symbol, int type, string comment) {
- Alert("-------- orders total: ", OrdersTotal());
- for (int cc = OrdersTotal() - 1; cc >= 0; cc--) {
- ulong ticket = OrderGetTicket(cc);
- if (OrderSelect(ticket)) {
- ENUM_ORDER_TYPE orderType = OrderGetInteger(ORDER_TYPE);
- string orderSymbol = OrderGetString(ORDER_SYMBOL);
- string orderComment = OrderGetString(ORDER_COMMENT);
- int orderMagicNumber = OrderGetInteger(ORDER_MAGIC);
- if(type != 0) {
- if(orderType != type) continue;
- }
- if(magicNo > 0) {
- if(orderMagicNumber != magicNo) continue;
- }
- if(symbol != "Any") {
- if(symbol == "NULL" || symbol == "Current") {
- symbol = Symbol();
- }
- if(orderSymbol != symbol) continue;
- }
- if(comment != "" && comment != NULL) {
- if(StringFind(orderComment, comment) == -1) continue;
- }
- // otherwise we found the order
- return(true);
- }
- }
- return(false);
- }
- /*
- //+------------------------------------------------------------------+
- bool sqSelectPendingOrderByDir(int magicNumber, string symbol, int direction, string comment) {
- for (int cc = OrdersTotal() - 1; cc >= 0; cc--) {
- ulong ticket = OrderGetTicket(cc);
- if (OrderSelect(ticket)) {
- ENUM_ORDER_TYPE orderType = OrderGetInteger(ORDER_TYPE);
- string orderSymbol = OrderGetString(ORDER_SYMBOL);
- string orderComment = OrderGetString(ORDER_COMMENT);
- double orderVolume = OrderGetDouble(ORDER_VOLUME_INITIAL);
- double orderOpenPrice = OrderGetDouble(ORDER_PRICE_OPEN);
- double orderCurrentPrice = OrderGetDouble(ORDER_PRICE_CURRENT);
- int orderMagicNumber = OrderGetInteger(ORDER_MAGIC);
- if(direction != 0) {
- if(direction > 0 && orderType != ORDER_TYPE_BUY_STOP && orderType != ORDER_TYPE_BUY_LIMIT) continue;
- if(direction < 0 && orderType != ORDER_TYPE_SELL_STOP && orderType != ORDER_TYPE_SELL_LIMIT) continue;
- }
- if(magicNumber != 0) {
- if(orderMagicNumber != magicNumber) continue;
- }
- if(symbol != "Any") {
- if(symbol == "NULL" || symbol == "Current") {
- symbol = Symbol();
- }
- if(orderSymbol != symbol) continue;
- }
- if(comment != "") {
- if(StringFind(orderComment, comment) == -1) continue;
- }
- // otherwise we found the order
- return(true);
- }
- }
- return(false);
- }
- //+------------------------------------------------------------------+
- */
- bool sqDeletePendingOrder(int ticket) {
- Verbose(" Deleting pending order, ticket: " + ticket);
- ENUM_ORDER_TYPE orderType = OrderGetInteger(ORDER_TYPE);
- if(orderType == ORDER_TYPE_BUY || orderType == ORDER_TYPE_SELL) {
- Verbose("Trying to delete non-pending order");
- return(false);
- }
- if(!sqCheckConnected()) {
- return(false);
- }
- GetLastError(); // clear the global variable.
- int error = 0;
- int retries = 0;
- bool result;
- while (true) {
- if (IsTradeAllowed()) {
- result = OrderDelete(ticket);
- if(result) {
- Verbose("Order deleted successfuly");
- return(true);
- }
- }
- retries++;
- if(!sqProcessErrors(retries, GetLastError())) {
- return(-1);
- }
- }
- }
- bool OrderDelete(ulong ticket){
- ZeroMemory(mrequest);
- mrequest.action = TRADE_ACTION_REMOVE;
- mrequest.magic = magicNumber;
- mrequest.order = ticket;
- //--- action and return the result
- return(OrderSend(mrequest, mresult));
- }
- bool IsTesting(){
- return MQLInfoInteger(MQL_TESTER);
- }
- //+------------------------------------------------------------------+
- double sleepPeriod = 500; // 0.5 s
- double maxSleepPeriod = 20000; // 20 s.
- void sqSleep() {
- if(IsTesting()) return;
- Sleep(sleepPeriod);
- int periods = maxSleepPeriod / sleepPeriod;
- for(int i=0; i<periods; i++) {
- if (MathRand() > 16383) {
- // 50% chance of quitting
- break;
- }
- Sleep(sleepPeriod);
- }
- }
- int sqGetDirectionFromOrderType(int orderType) {
- if(orderType == ORDER_TYPE_BUY || orderType == ORDER_TYPE_BUY_STOP || orderType == ORDER_TYPE_BUY_LIMIT) {
- return(1);
- } else {
- return(-1);
- }
- }
- //+------------------------------------------------------------------+
- bool sqIsPendingOrder(int orderType) {
- if(orderType != ORDER_TYPE_BUY && orderType != ORDER_TYPE_SELL) {
- return(true);
- }
- return(false);
- }
- //+------------------------------------------------------------------+
- string sqGetOrderTypeAsString(int type) {
- switch(type) {
- case ORDER_TYPE_BUY: return("Buy");
- case ORDER_TYPE_SELL: return("Sell");
- case ORDER_TYPE_BUY_LIMIT: return("Buy Limit");
- case ORDER_TYPE_BUY_STOP: return("Buy Stop");
- case ORDER_TYPE_SELL_LIMIT: return("Sell Limit");
- case ORDER_TYPE_SELL_STOP: return("Sell Stop");
- }
- return("Unknown");
- }
- //+------------------------------------------------------------------+
- void sqInitInfoPanel() {
- ObjectCreate(ChartID(), "line1", OBJ_LABEL, 0, 0, 0);
- ObjectSetInteger(ChartID(), "line1", OBJPROP_CORNER, sqLabelCorner);
- ObjectSetInteger(ChartID(), "line1", OBJPROP_YDISTANCE, sqOffsetVertical + 0);
- ObjectSetInteger(ChartID(), "line1", OBJPROP_XDISTANCE, sqOffsetHorizontal);
- setupLabel("line1", sqStrategyName, 9);
- ObjectCreate(ChartID(), "linec", OBJ_LABEL, 0, 0, 0);
- ObjectSetInteger(ChartID(), "linec", OBJPROP_CORNER, sqLabelCorner);
- ObjectSetInteger(ChartID(), "linec", OBJPROP_YDISTANCE, sqOffsetVertical + 16 );
- ObjectSetInteger(ChartID(), "linec", OBJPROP_XDISTANCE, sqOffsetHorizontal);
- setupLabel("linec", "Generated by StrategyQuant EA Wizard");
- ObjectCreate(ChartID(), "line2", OBJ_LABEL, 0, 0, 0);
- ObjectSetInteger(ChartID(), "line2", OBJPROP_CORNER, sqLabelCorner);
- ObjectSetInteger(ChartID(), "line2", OBJPROP_YDISTANCE, sqOffsetVertical + 28);
- ObjectSetInteger(ChartID(), "line2", OBJPROP_XDISTANCE, sqOffsetHorizontal);
- setupLabel("line2", "------------------------------------------");
- ObjectCreate(ChartID(), "lines", OBJ_LABEL, 0, 0, 0);
- ObjectSetInteger(ChartID(), "lines", OBJPROP_CORNER, sqLabelCorner);
- ObjectSetInteger(ChartID(), "lines", OBJPROP_YDISTANCE, sqOffsetVertical + 44);
- ObjectSetInteger(ChartID(), "lines", OBJPROP_XDISTANCE, sqOffsetHorizontal);
- setupLabel("lines", "Last Signal: -", 9);
- ObjectCreate(ChartID(), "lineopl", OBJ_LABEL, 0, 0, 0);
- ObjectSetInteger(ChartID(), "lineopl", OBJPROP_CORNER, sqLabelCorner);
- ObjectSetInteger(ChartID(), "lineopl", OBJPROP_YDISTANCE, sqOffsetVertical + 60);
- ObjectSetInteger(ChartID(), "lineopl", OBJPROP_XDISTANCE, sqOffsetHorizontal);
- setupLabel("lineopl", "Open P/L: -");
- ObjectCreate(ChartID(), "linea", OBJ_LABEL, 0, 0, 0);
- ObjectSetInteger(ChartID(), "linea", OBJPROP_CORNER, sqLabelCorner);
- ObjectSetInteger(ChartID(), "linea", OBJPROP_YDISTANCE, sqOffsetVertical + 76);
- ObjectSetInteger(ChartID(), "linea", OBJPROP_XDISTANCE, sqOffsetHorizontal);
- setupLabel("linea", "Account Balance: -");
- ObjectCreate(ChartID(), "lineto", OBJ_LABEL, 0, 0, 0);
- ObjectSetInteger(ChartID(), "lineto", OBJPROP_CORNER, sqLabelCorner);
- ObjectSetInteger(ChartID(), "lineto", OBJPROP_YDISTANCE, sqOffsetVertical + 92);
- ObjectSetInteger(ChartID(), "lineto", OBJPROP_XDISTANCE, sqOffsetHorizontal);
- setupLabel("lineto", "Total profits/losses so far: -/-");
- ObjectCreate(ChartID(), "linetp", OBJ_LABEL, 0, 0, 0);
- ObjectSetInteger(ChartID(), "linetp", OBJPROP_CORNER, sqLabelCorner);
- ObjectSetInteger(ChartID(), "linetp", OBJPROP_YDISTANCE, sqOffsetVertical + 108);
- ObjectSetInteger(ChartID(), "linetp", OBJPROP_XDISTANCE, sqOffsetHorizontal);
- setupLabel("linetp", "Total P/L so far: -");
- }
- //+------------------------------------------------------------------+
- void sqDeinitInfoPanel() {
- ObjectDelete(ChartID(), "line1");
- ObjectDelete(ChartID(), "linec");
- ObjectDelete(ChartID(), "line2");
- ObjectDelete(ChartID(), "lines");
- ObjectDelete(ChartID(), "lineopl");
- ObjectDelete(ChartID(), "linea");
- ObjectDelete(ChartID(), "lineto");
- ObjectDelete(ChartID(), "linetp");
- }
- //+------------------------------------------------------------------+
- void sqTextFillOpens() {
- setupLabel("lineopl", "Open P/L: "+DoubleToString(sqGetOpenPLInMoney(0), 2));
- setupLabel("linea", "Account Balance: "+DoubleToString(AccountInfoDouble(ACCOUNT_BALANCE), 2));
- }
- //+------------------------------------------------------------------+
- void setupLabel(string objectName, string text, const string font = "Tahoma", const int fontSize = 8, const color objColor = NULL){
- color clr = objColor == NULL ? sqLabelColor : objColor;
- ObjectSetString(ChartID(), objectName, OBJPROP_TEXT, text);
- ObjectSetString(ChartID(), objectName, OBJPROP_FONT, font);
- ObjectSetInteger(ChartID(), objectName, OBJPROP_FONTSIZE, fontSize);
- ObjectSetInteger(ChartID(), objectName, OBJPROP_COLOR, clr);
- }
- //+------------------------------------------------------------------+
- void sqTextFillTotals() {
- setupLabel("lineto", "Total profits/losses so far: "+sqGetTotalProfits(0, 100)+"/"+sqGetTotalLosses(0, 100));
- setupLabel("linetp", "Total P/L so far: "+DoubleToString(sqGetTotalClosedPLInMoney(0, 1000), 2));
- }
- //+------------------------------------------------------------------+
- double sqGetOpenPLInMoney(int orderMagicNumber) {
- double pl = 0;
- for(int i=PositionsTotal(); i>=0; i--) {
- ulong ticket = PositionGetTicket(i);
- if(PositionSelectByTicket(ticket)){
- int magic = PositionGetInteger(POSITION_MAGIC);
- double profit = PositionGetDouble(POSITION_PROFIT);
- if(orderMagicNumber != 0 && magic != orderMagicNumber) continue;
- pl += profit;
- }
- }
- return(pl);
- }
- //+------------------------------------------------------------------+
- int sqGetTotalProfits(int orderMagicNumber, int numberOfLastOrders) {
- int count = 0;
- int profits = 0;
- HistorySelect(startTime, getTime(0));
- for(int i=HistoryDealsTotal(); i>=0; i--) {
- ulong ticket = HistoryDealGetTicket(i);
- if (HistoryDealGetString(ticket, DEAL_SYMBOL) == Symbol() && HistoryDealGetInteger(ticket,DEAL_ENTRY) == DEAL_ENTRY_OUT) {
- int magic = HistoryDealGetInteger(ticket, DEAL_MAGIC);
- if(orderMagicNumber == 0 || magic == orderMagicNumber) {
- // return the P/L of last order
- // or return the P/L of last order with given Magic Number
- count++;
- if(HistoryDealGetDouble(ticket, DEAL_PROFIT) > 0) {
- profits++;
- }
- if(count >= numberOfLastOrders) break;
- }
- }
- }
- return(profits);
- }
- //+------------------------------------------------------------------+
- int sqGetTotalLosses(int orderMagicNumber, int numberOfLastOrders) {
- int count = 0;
- int losses = 0;
- HistorySelect(startTime, getTime(0));
- for(int i=HistoryDealsTotal(); i>=0; i--) {
- ulong ticket = HistoryDealGetTicket(i);
- if (HistoryDealGetString(ticket, DEAL_SYMBOL) == Symbol() && HistoryDealGetInteger(ticket,DEAL_ENTRY) == DEAL_ENTRY_OUT) {
- int magic = HistoryDealGetInteger(ticket, DEAL_MAGIC);
- if(orderMagicNumber == 0 || magic == orderMagicNumber) {
- // return the P/L of last order
- // or return the P/L of last order with given Magic Number
- count++;
- if(HistoryDealGetDouble(ticket, DEAL_PROFIT) < 0) {
- losses++;
- }
- if(count >= numberOfLastOrders) break;
- }
- }
- }
- return(losses);
- }
- //+------------------------------------------------------------------+
- double sqGetTotalClosedPLInMoney(int orderMagicNumber, int numberOfLastOrders) {
- double pl = 0;
- int count = 0;
- HistorySelect(startTime, getTime(0));
- for(int i=HistoryDealsTotal(); i>=0; i--) {
- ulong ticket = HistoryDealGetTicket(i);
- if (HistoryDealGetString(ticket, DEAL_SYMBOL) == Symbol() && HistoryDealGetInteger(ticket,DEAL_ENTRY) == DEAL_ENTRY_OUT) {
- int magic = HistoryDealGetInteger(ticket, DEAL_MAGIC);
- if(orderMagicNumber == 0 || magic == orderMagicNumber) {
- // return the P/L of last order or the P/L of last order with given Magic Number
- count++;
- pl = pl + HistoryDealGetDouble(ticket, DEAL_PROFIT);
- if(count >= numberOfLastOrders) break;
- }
- }
- }
- return(pl);
- }
- //+------------------------------------------------------------------+
- double sqMMRiskPercentage(string symbol, int orderType, double price, double sl, double RiskInPercent, double LotsIfNoMM, double MaximumLots, double BaseCurrencyExchangeRate) {
- Verbose("Computing Money Management for order - Risk fixed % of account balance");
- double slSize = sqConvertToPips(symbol, MathAbs(price - sl));
- if(slSize <= 0) {
- Verbose("Computing Money Management - Stop Loss is zero, using Lots if no MM: ", LotsIfNoMM);
- return(LotsIfNoMM);
- }
- Verbose("Price: ", price, ", SL: ", sl, ", SLSize: ", slSize, ", RiskInPercent: ", RiskInPercent);
- double LotSize=0;
- if(RiskInPercent < 0 ) {
- Verbose("Computing Money Management - Incorrect RiskInPercent size, it must be above 0");
- return(0);
- }
- double riskPerTrade = (BaseCurrencyExchangeRate * AccountInfoDouble(ACCOUNT_BALANCE) * (RiskInPercent / 100.0));
- if(slSize <= 0) {
- Verbose("Computing Money Management - Incorrect StopLossPips size, it must be above 0");
- return(0);
- }
- Verbose("Risk per trade: ", riskPerTrade);
- double TickSize = SymbolInfoDouble(Symbol(), SYMBOL_TRADE_TICK_SIZE);
- double TickValue = SymbolInfoDouble(Symbol(), SYMBOL_TRADE_TICK_VALUE);
- double PointValue = SymbolInfoDouble(Symbol(), SYMBOL_POINT);
- double LotStep = SymbolInfoDouble(Symbol(), SYMBOL_VOLUME_STEP);
- if(_Digits == 1 || _Digits == 3 || _Digits == 5) {
- slSize = 10 * slSize; // conversion from pips to points
- }
- Verbose("Computing Money Management - SL: ", slSize, ", Account Balance: ", AccountInfoDouble(ACCOUNT_BALANCE),", Tick value: ", TickValue,", Point: ", PointValue, ", LotStep: ", LotStep,", Tick size: ", TickSize);
- if(slSize>0 && TickValue>0)
- {
- LotSize = TickSize * riskPerTrade / (slSize * TickValue * PointValue );
- int err=GetLastError();
- if(err==4013)
- { //ERR_ZERO_DIVIDE
- Verbose("Err: division by zero: StopLoss:",slSize," TickValue:",TickValue," LotSize:",LotSize);
- return(-1);
- }
- }
- //--- MAXLOT and MINLOT management
- double Smallest_Lot = SymbolInfoDouble(Symbol(), SYMBOL_VOLUME_MIN);
- double Largest_Lot = SymbolInfoDouble(Symbol(), SYMBOL_VOLUME_MAX);
- Verbose("Computing Money Management - Smallest_Lot: ", Smallest_Lot, ", Largest_Lot: ", Largest_Lot,", Computed LotSize: ", LotSize);
- if (LotSize < Smallest_Lot) LotSize = Smallest_Lot;
- if (LotSize > Largest_Lot) LotSize = Largest_Lot;
- if(LotSize > MaximumLots) {
- LotSize = MaximumLots;
- }
- //--------------------------------------------
- //--- LotSize rounded regarding Broker LOTSTEP
- if(LotStep==1) {
- LotSize=NormalizeDouble(LotSize,0);
- }
- if(LotStep==0.1) {
- LotSize=NormalizeDouble(LotSize,1);
- }
- if(LotStep==0.01) {
- LotSize=NormalizeDouble(LotSize,2);
- }
- if(LotStep==0.001) {
- LotSize=NormalizeDouble(LotSize,3);
- }
- //--------------------------------------------
- return (LotSize);
- }
- //+------------------------------------------------------------------+
- double sqGetSLLevel(string symbol, int orderType, double price, bool valueInPips, double value) {
- return(sqGetSLPTLevel(-1.0, symbol, orderType, price, valueInPips, value));
- }
- //+------------------------------------------------------------------+
- double sqGetPTLevel(string symbol, int orderType, double price, bool valueInPips, double value) {
- return(sqGetSLPTLevel(1.0, symbol, orderType, price, valueInPips, value));
- }
- //+------------------------------------------------------------------+
- double sqGetSLPTLevel(double SLorPT, string symbol, int orderType, double price, bool valueInPips, double value) {
- string _symbol = correctSymbol(symbol);
- if(valueInPips) {
- // convert from pips to real points
- value = sqConvertToRealPips(_symbol, value);
- }
- if(price == 0) {
- // price can be zero for market order
- if(orderType == ORDER_TYPE_BUY) {
- price = sqGetAsk(_symbol);
- } else {
- price = sqGetBid(_symbol);
- }
- }
- if(orderType == ORDER_TYPE_BUY || orderType == ORDER_TYPE_BUY_STOP || orderType == ORDER_TYPE_BUY_LIMIT) {
- return (price + (SLorPT * value));
- } else {
- return (price - (SLorPT * value));
- }
- }
- //+------------------------------------------------------------------+
- double sqBarRange(string symbol, int timeframe, int shift) {
- string curSymbol = (symbol == "NULL" || symbol == "Current") ? _Symbol : symbol;
- return(iHigh(curSymbol, timeframe, shift) - iLow(symbol, timeframe, shift));
- }
- //+------------------------------------------------------------------+
- double sqConvertToRealPips(string symbol, double value) {
- if(symbol == "NULL" || symbol == "Current") {
- return(gPointCoef * value);
- }
- double pointCoef = sqGetPointCoef(symbol);
- return(pointCoef * value);
- }
- //+------------------------------------------------------------------+
- double sqGetPointCoef(string symbol) {
- if(symbol == "NULL" || symbol == "Current") {
- return(gPointCoef);
- }
- // recognize point coeficient
- double realDigits = SymbolInfoInteger(symbol, SYMBOL_DIGITS);
- if(realDigits == 4 || realDigits == 5) {
- realDigits -= 1;
- }
- double pointPow = MathPow(10, realDigits);
- return(1 / pointPow);
- }
- //+------------------------------------------------------------------+
- bool sqDoublesAreEqual(double n1, double n2) {
- string st1 = DoubleToString(n1, _Digits);
- string st2 = DoubleToString(n2, _Digits);
- return (st1 == st2);
- }
- //+------------------------------------------------------------------+
- double sqHighest(string symbol, int timeframe, int period, int shift) {
- double maxnum = -100000000;
- double val;
- for(int i=shift; i<shift+period; i++) {
- if(symbol == NULL || symbol == "NULL" || symbol == "Current") {
- val = iHigh(NULL, timeframe, i);
- } else {
- val = iHigh(symbol, timeframe, i);
- }
- if(val > maxnum) {
- maxnum = val;
- }
- }
- return(maxnum);
- }
- //+------------------------------------------------------------------+
- double sqHighestIndex(string symbol, int timeframe, int period, int shift) {
- double maxnum = -100000000;
- int index;
- double val;
- for(int i=shift; i<shift+period; i++) {
- if(symbol == NULL || symbol == "NULL" || symbol == "Current") {
- val = iHigh(NULL, timeframe, i);
- } else {
- val = iHigh(symbol, timeframe, i);
- }
- if(val > maxnum) {
- maxnum = val;
- index = i;
- }
- }
- return(index);
- }
- //+------------------------------------------------------------------+
- double sqLowest(string symbol, int timeframe, int period, int shift) {
- double minnum = 100000000;
- double val;
- for(int i=shift; i<shift+period; i++) {
- if(symbol == NULL || symbol == "NULL" || symbol == "Current") {
- val = iLow(NULL, timeframe, i);
- } else {
- val = iLow(symbol, timeframe, i);
- }
- if(val < minnum) {
- minnum = val;
- }
- }
- return(minnum);
- }
- //+------------------------------------------------------------------+
- double sqLowestIndex(string symbol, int timeframe, int period, int shift) {
- double minnum = 100000000;
- int index;
- double val;
- for(int i=shift; i<shift+period; i++) {
- if(symbol == NULL || symbol == "NULL" || symbol == "Current") {
- val = iLow(NULL, timeframe, i);
- } else {
- val = iLow(symbol, timeframe, i);
- }
- if(val < minnum) {
- minnum = val;
- index = i;
- }
- }
- return(index);
- }
- //+------------------------------------------------------------------+
- double sqBiggestRange(string symbol, int timeframe, int period, int shift) {
- double maxnum = -100000000;
- double range;
- for(int i=shift; i<shift+period; i++) {
- if(symbol == NULL || symbol == "NULL" || symbol == "Current") {
- range = iHigh(NULL, timeframe, i) - iLow(NULL, timeframe, i);
- } else {
- range = iHigh(symbol, timeframe, i) - iLow(symbol, timeframe, i);
- }
- if(range > maxnum) {
- maxnum = range;
- }
- }
- return(maxnum);
- }
- //+------------------------------------------------------------------+
- double sqSmallestRange(string symbol, int timeframe, int period, int shift) {
- double minnum = 100000000;
- double range;
- for(int i=shift; i<shift+period; i++) {
- if(symbol == NULL || symbol == "NULL" || symbol == "Current") {
- range = iHigh(NULL, timeframe, i) - iLow(NULL, timeframe, i);
- } else {
- range = iHigh(symbol, timeframe, i) - iLow(symbol, timeframe, i);
- }
- if(range < minnum) {
- minnum = range;
- }
- }
- return(minnum);
- }
- //+------------------------------------------------------------------+
- void sqDrawUpArrow(int shift) {
- string name;
- StringConcatenate(name, "Arrow_", MathRand());
- ObjectCreate(ChartID(), name, OBJ_ARROW, 0, getTime(shift), getHigh(shift) - 20 * _Point); //draw an up arrow
- ObjectSetInteger(ChartID(), name, OBJPROP_STYLE, STYLE_SOLID);
- ObjectSetInteger(ChartID(), name, OBJPROP_ARROWCODE, OBJ_ARROW_UP);
- ObjectSetInteger(ChartID(), name, OBJPROP_COLOR, clrGreen);
- }
- //+------------------------------------------------------------------+
- void sqDrawDownArrow(int shift) {
- string name;
- StringConcatenate(name, "Arrow_", MathRand());
- ObjectCreate(ChartID(), name, OBJ_ARROW, 0, getTime(shift), getHigh(shift) + 140 * _Point); //draw an down arrow
- ObjectSetInteger(ChartID(), name, OBJPROP_STYLE, STYLE_SOLID);
- ObjectSetInteger(ChartID(), name, OBJPROP_ARROWCODE, OBJ_ARROW_DOWN);
- ObjectSetInteger(ChartID(), name, OBJPROP_COLOR, clrRed);
- }
- //+------------------------------------------------------------------+
- double sqHeikenAshi(string symbol, ENUM_TIMEFRAMES timeframe, string mode, int shift) {
- int handle = iCustom(correctSymbol(symbol), timeframe, "Examples\\Heiken_Ashi", 0,0,0,0);
- if(mode == "Open") {
- return(sqGetIndicatorValue(handle, 0, shift));
- }
- else if(mode == "Close") {
- return(sqGetIndicatorValue(handle, 3, shift));
- }
- else if(mode == "High") {
- return(MathMax(sqGetIndicatorValue(handle, 0, shift), sqGetIndicatorValue(handle, 1, shift)));
- }
- else if(mode == "Low") {
- return(MathMin(sqGetIndicatorValue(handle, 0, shift), sqGetIndicatorValue(handle, 2, shift)));
- }
- return(-1);
- }
- //+------------------------------------------------------------------+
- double sqDaily(string symbol, int tf, string mode, int shift) {
- if(symbol == "NULL" || symbol == "Current") {
- if(mode == "Open") {
- return(iOpen(NULL, PERIOD_D1, shift));
- }
- if(mode == "Close") {
- return(iClose(NULL, PERIOD_D1, shift));
- }
- if(mode == "High") {
- return(iHigh(NULL, PERIOD_D1, shift));
- }
- if(mode == "Low") {
- return(iLow(NULL, PERIOD_D1, shift));
- }
- } else {
- if(mode == "Open") {
- return(iOpen(symbol, PERIOD_D1, shift));
- }
- if(mode == "Close") {
- return(iClose(symbol, PERIOD_D1, shift));
- }
- if(mode == "High") {
- return(iHigh(symbol, PERIOD_D1, shift));
- }
- if(mode == "Low") {
- return(iLow(symbol, PERIOD_D1, shift));
- }
- }
- return(-1);
- }
- //+------------------------------------------------------------------+
- double sqHighestInRange(string symbol, int timeframe, string timeFrom, string timeTo) {
- int indexTo = -1;
- int indexFrom = -1;
- int i;
- // find index of bar for timeTo
- for(i=1; i<=2000; i++) {
- if(TimeToString(getTime(i), TIME_MINUTES) == timeTo || (TimeToString(getTime(i), TIME_MINUTES) >= timeTo && TimeToString(getTime(i+1), TIME_MINUTES) < timeTo)) {
- //Log("Found timeTo: ", TimeToString(Time[i]));
- indexTo = i;
- break;
- }
- }
- if(indexTo == -1) {
- Log("Not found timeTo");
- return(-1);
- }
- // find index of bar for timeFrom
- for(i=indexTo+1; i<=2000; i++) {
- if(TimeToString(getTime(i), TIME_MINUTES) == timeFrom || (TimeToString(getTime(i), TIME_MINUTES) >= timeFrom && TimeToString(getTime(i+1), TIME_MINUTES) < timeFrom)) {
- //Log("Found timeFrom: ", TimeToString(Time[i]));
- indexFrom = i;
- break;
- }
- }
- if(indexFrom == -1) {
- Log("Not found time From");
- return(-1);
- }
- double value = -100000000.0;
- for(i=indexTo; i<=indexFrom; i++) {
- if(symbol == "NULL") {
- value = MathMax(value, iHigh(NULL, timeframe, i));
- } else {
- value = MathMax(value, iHigh(symbol, timeframe, i));
- }
- }
- return(value);
- }
- //+------------------------------------------------------------------+
- double sqLowestInRange(string symbol, int timeframe, string timeFrom, string timeTo) {
- int indexTo = -1;
- int indexFrom = -1;
- int i;
- // find index of bar for timeTo
- for(i=1; i<=2000; i++) {
- if(TimeToString(getTime(i), TIME_MINUTES) == timeTo || (TimeToString(getTime(i), TIME_MINUTES) >= timeTo && TimeToString(getTime(i+1), TIME_MINUTES) < timeTo)) {
- //Log("Found timeTo: ", TimeToString(Time[i]));
- indexTo = i;
- break;
- }
- }
- if(indexTo == -1) {
- Log("Not found timeTo");
- return(-1);
- }
- // find index of bar for timeFrom
- for(i=indexTo+1; i<=2000; i++) {
- if(TimeToString(getTime(i), TIME_MINUTES) == timeFrom || (TimeToString(getTime(i), TIME_MINUTES) >= timeFrom && TimeToString(getTime(i+1), TIME_MINUTES) < timeFrom)) {
- //Log("Found timeFrom: ", TimeToString(Time[i]));
- indexFrom = i;
- break;
- }
- }
- if(indexFrom == -1) {
- Log("Not found time From");
- return(-1);
- }
- double value = 100000000.0;
- for(i=indexTo; i<=indexFrom; i++) {
- if(symbol == "NULL") {
- value = MathMin(value, iLow(NULL, timeframe, i));
- } else {
- value = MathMin(value, iLow(symbol, timeframe, i));
- }
- }
- return(value);
- }
- //+------------------------------------------------------------------+
- string sqGetDate(int day, int month, int year) {
- string strYear = year;
- string strMonth = month;
- if(month < 10) strMonth = "0"+strMonth;
- string strDay = day;
- if(day < 10) strDay = "0"+strDay;
- return(StringConcatenate(strYear, ".", strMonth, ".", strDay));
- }
- //+------------------------------------------------------------------+
- string sqGetTime(int hour, int minute, int second) {
- string strHour = hour;
- if(hour < 10) strHour = "0"+strHour;
- string strMinute = minute;
- if(minute < 10) strMinute = "0"+strMinute;
- string strSecond = second;
- if(second < 10) strSecond = "0"+strSecond;
- return(StringConcatenate(strHour, ":", strMinute, ":", strSecond));
- }
- //+------------------------------------------------------------------+
- double sqSafeDivide(double var1, double var2) {
- if(var2 == 0) return(100000000);
- return(var1/var2);
- }
- //+------------------------------------------------------------------+
- bool sqIsGreaterThanZero(double value) {
- double diff = value - 0;
- if(diff > 0.0000000001) {
- return(true);
- }
- return(false);
- }
- //+------------------------------------------------------------------+
- bool sqIsLowerThanZero(double value) {
- double diff = 0 - value;
- if(diff > 0.0000000001) {
- return(true);
- }
- return(false);
- }
- //+------------------------------------------------------------------+
- //+ Candle Pattern functions
- //+------------------------------------------------------------------+
- bool sqBearishEngulfing(string symbol, int shift) {
- double O = getOpen(shift);
- double O1 = getOpen(shift+1);
- double C = getClose(shift);
- double C1 = getClose(shift+1);
- if ((C1>O1)&&(O>C)&&(O>=C1)&&(O1>=C)&&((O-C)>(C1-O1))) {
- return(true);
- }
- return(false);
- }
- //+------------------------------------------------------------------+
- bool sqBullishEngulfing(string symbol, int shift) {
- double O = getOpen(shift);
- double O1 = getOpen(shift+1);
- double C = getClose(shift);
- double C1 = getClose(shift+1);
- if ((O1>C1)&&(C>O)&&(C>=O1)&&(C1>=O)&&((C-O)>(O1-C1))) {
- return(true);
- }
- return(false);
- }
- //+------------------------------------------------------------------+
- bool sqDarkCloudCover(string symbol, int shift) {
- double L = getLow(shift);
- double H = getHigh(shift);
- double O = getOpen(shift);
- double O1 = getOpen(shift+1);
- double C = getClose(shift);
- double C1 = getClose(shift+1);
- double CL = H-L;
- double OC_HL;
- if((H - L) != 0) {
- OC_HL = (O-C)/(H-L);
- } else {
- OC_HL = 0;
- }
- double Piercing_Line_Ratio = 0.5;
- double Piercing_Candle_Length = 10;
- if ((C1>O1)&&(((C1+O1)/2)>C)&&(O>C)&&(C>O1)&&(OC_HL>Piercing_Line_Ratio)&&((CL>=Piercing_Candle_Length*sqGetPointCoef(symbol)))) {
- return(true);
- }
- return(false);
- }
- //+------------------------------------------------------------------+
- bool sqDoji(string symbol, int shift) {
- if(MathAbs(getOpen(shift) - getClose(shift))*sqGetPointCoef(symbol) < 0.6) {
- return(true);
- }
- return(false);
- }
- //+------------------------------------------------------------------+
- bool sqHammer(string symbol, int shift) {
- double H = getHigh(shift);
- double L = getLow(shift);
- double L1 = getLow(shift+1);
- double L2 = getLow(shift+2);
- double L3 = getLow(shift+3);
- double O = getOpen(shift);
- double C = getClose(shift);
- double CL = H-L;
- double BodyLow, BodyHigh;
- double Candle_WickBody_Percent = 0.9;
- double CandleLength = 12;
- if (O > C) {
- BodyHigh = O;
- BodyLow = C;
- } else {
- BodyHigh = C;
- BodyLow = O;
- }
- double LW = BodyLow-L;
- double UW = H-BodyHigh;
- double BLa = MathAbs(O-C);
- double BL90 = BLa*Candle_WickBody_Percent;
- double pipValue = sqGetPointCoef(symbol);
- if ((L<=L1)&&(L<L2)&&(L<L3)) {
- if (((LW/2)>UW)&&(LW>BL90)&&(CL>=(CandleLength*pipValue))&&(O!=C)&&((LW/3)<=UW)&&((LW/4)<=UW)) {
- return(true);
- }
- if (((LW/3)>UW)&&(LW>BL90)&&(CL>=(CandleLength*pipValue))&&(O!=C)&&((LW/4)<=UW)) {
- return(true);
- }
- if (((LW/4)>UW)&&(LW>BL90)&&(CL>=(CandleLength*pipValue))&&(O!=C)) {
- return(true);
- }
- }
- return(false);
- }
- //+------------------------------------------------------------------+
- bool sqPiercingLine(string symbol, int shift) {
- double L = getLow(shift);
- double H = getHigh(shift);
- double O = getOpen(shift);
- double O1 = getOpen(shift+1);
- double C = getClose(shift);
- double C1 = getClose(shift+1);
- double CL = H-L;
- double CO_HL;
- if((H - L) != 0) {
- CO_HL = (C-O)/(H-L);
- } else {
- CO_HL = 0;
- }
- double Piercing_Line_Ratio = 0.5;
- double Piercing_Candle_Length = 10;
- if ((C1<O1)&&(((O1+C1)/2)<C)&&(O<C) && (CO_HL>Piercing_Line_Ratio)&&(CL>=(Piercing_Candle_Length*sqGetPointCoef(symbol)))) {
- return(true);
- }
- return(false);
- }
- //+------------------------------------------------------------------+
- bool sqShootingStar(string symbol, int shift) {
- double L = getLow(shift);
- double H = getHigh(shift);
- double H1 = getHigh(shift+1);
- double H2 = getHigh(shift+2);
- double H3 = getHigh(shift+3);
- double O = getOpen(shift);
- double C = getClose(shift);
- double CL = H-L;
- double BodyLow, BodyHigh;
- double Candle_WickBody_Percent = 0.9;
- double CandleLength = 12;
- if (O > C) {
- BodyHigh = O;
- BodyLow = C;
- } else {
- BodyHigh = C;
- BodyLow = O;
- }
- double LW = BodyLow-L;
- double UW = H-BodyHigh;
- double BLa = MathAbs(O-C);
- double BL90 = BLa*Candle_WickBody_Percent;
- double pipValue = sqGetPointCoef(symbol);
- if ((H>=H1)&&(H>H2)&&(H>H3)) {
- if (((UW/2)>LW)&&(UW>(2*BL90))&&(CL>=(CandleLength*pipValue))&&(O!=C)&&((UW/3)<=LW)&&((UW/4)<=LW)) {
- return(true);
- }
- if (((UW/3)>LW)&&(UW>(2*BL90))&&(CL>=(CandleLength*pipValue))&&(O!=C)&&((UW/4)<=LW)) {
- return(true);
- }
- if (((UW/4)>LW)&&(UW>(2*BL90))&&(CL>=(CandleLength*pipValue))&&(O!=C)) {
- return(true);
- }
- }
- return(false);
- }
- //+------------------------------------------------------------------+
- //| returns runtime error code description |
- //+------------------------------------------------------------------+
- string ErrorDescription(int err_code)
- {
- //---
- switch(err_code)
- {
- //--- Constant Description
- case ERR_SUCCESS: return("The operation completed successfully");
- case ERR_INTERNAL_ERROR: return("Unexpected internal error");
- case ERR_WRONG_INTERNAL_PARAMETER: return("Wrong parameter in the inner call of the client terminal function");
- case ERR_INVALID_PARAMETER: return("Wrong parameter when calling the system function");
- case ERR_NOT_ENOUGH_MEMORY: return("Not enough memory to perform the system function");
- case ERR_STRUCT_WITHOBJECTS_ORCLASS: return("The structure contains objects of strings and/or dynamic arrays and/or structure of such objects and/or classes");
- case ERR_INVALID_ARRAY: return("Array of a wrong type, wrong size, or a damaged object of a dynamic array");
- case ERR_ARRAY_RESIZE_ERROR: return("Not enough memory for the relocation of an array, or an attempt to change the size of a static array");
- case ERR_STRING_RESIZE_ERROR: return("Not enough memory for the relocation of string");
- case ERR_NOTINITIALIZED_STRING: return("Not initialized string");
- case ERR_INVALID_DATETIME: return("Invalid date and/or time");
- case ERR_ARRAY_BAD_SIZE: return("Requested array size exceeds 2 GB");
- case ERR_INVALID_POINTER: return("Wrong pointer");
- case ERR_INVALID_POINTER_TYPE: return("Wrong type of pointer");
- case ERR_FUNCTION_NOT_ALLOWED: return("System function is not allowed to call");
- //--- Charts
- case ERR_CHART_WRONG_ID: return("Wrong chart ID");
- case ERR_CHART_NO_REPLY: return("Chart does not respond");
- case ERR_CHART_NOT_FOUND: return("Chart not found");
- case ERR_CHART_NO_EXPERT: return("No Expert Advisor in the chart that could handle the event");
- case ERR_CHART_CANNOT_OPEN: return("Chart opening error");
- case ERR_CHART_CANNOT_CHANGE: return("Failed to change chart symbol and period");
- case ERR_CHART_WRONG_PARAMETER: return("Wrong parameter");
- case ERR_CHART_CANNOT_CREATE_TIMER: return("Failed to create timer");
- case ERR_CHART_WRONG_PROPERTY: return("Wrong chart property ID");
- case ERR_CHART_SCREENSHOT_FAILED: return("Error creating screenshots");
- case ERR_CHART_NAVIGATE_FAILED: return("Error navigating through chart");
- case ERR_CHART_TEMPLATE_FAILED: return("Error applying template");
- case ERR_CHART_WINDOW_NOT_FOUND: return("Subwindow containing the indicator was not found");
- case ERR_CHART_INDICATOR_CANNOT_ADD: return("Error adding an indicator to chart");
- case ERR_CHART_INDICATOR_CANNOT_DEL: return("Error deleting an indicator from the chart");
- case ERR_CHART_INDICATOR_NOT_FOUND: return("Indicator not found on the specified chart");
- //--- Graphical Objects
- case ERR_OBJECT_ERROR: return("Error working with a graphical object");
- case ERR_OBJECT_NOT_FOUND: return("Graphical object was not found");
- case ERR_OBJECT_WRONG_PROPERTY: return("Wrong ID of a graphical object property");
- case ERR_OBJECT_GETDATE_FAILED: return("Unable to get date corresponding to the value");
- case ERR_OBJECT_GETVALUE_FAILED: return("Unable to get value corresponding to the date");
- //--- MarketInfo
- case ERR_MARKET_UNKNOWN_SYMBOL: return("Unknown symbol");
- case ERR_MARKET_NOT_SELECTED: return("Symbol is not selected in MarketWatch");
- case ERR_MARKET_WRONG_PROPERTY: return("Wrong identifier of a symbol property");
- case ERR_MARKET_LASTTIME_UNKNOWN: return("Time of the last tick is not known (no ticks)");
- case ERR_MARKET_SELECT_ERROR: return("Error adding or deleting a symbol in MarketWatch");
- //--- History Access
- case ERR_HISTORY_NOT_FOUND: return("Requested history not found");
- case ERR_HISTORY_WRONG_PROPERTY: return("Wrong ID of the history property");
- //--- Global_Variables
- case ERR_GLOBALVARIABLE_NOT_FOUND: return("Global variable of the client terminal is not found");
- case ERR_GLOBALVARIABLE_EXISTS: return("Global variable of the client terminal with the same name already exists");
- case ERR_MAIL_SEND_FAILED: return("Email sending failed");
- case ERR_PLAY_SOUND_FAILED: return("Sound playing failed");
- case ERR_MQL5_WRONG_PROPERTY: return("Wrong identifier of the program property");
- case ERR_TERMINAL_WRONG_PROPERTY: return("Wrong identifier of the terminal property");
- case ERR_FTP_SEND_FAILED: return("File sending via ftp failed");
- case ERR_NOTIFICATION_SEND_FAILED: return("Error in sending notification");
- //--- Custom Indicator Buffers
- case ERR_BUFFERS_NO_MEMORY: return("Not enough memory for the distribution of indicator buffers");
- case ERR_BUFFERS_WRONG_INDEX: return("Wrong indicator buffer index");
- //--- Custom Indicator Properties
- case ERR_CUSTOM_WRONG_PROPERTY: return("Wrong ID of the custom indicator property");
- //--- Account
- case ERR_ACCOUNT_WRONG_PROPERTY: return("Wrong account property ID");
- case ERR_TRADE_WRONG_PROPERTY: return("Wrong trade property ID");
- case ERR_TRADE_DISABLED: return("Trading by Expert Advisors prohibited");
- case ERR_TRADE_POSITION_NOT_FOUND: return("Position not found");
- case ERR_TRADE_ORDER_NOT_FOUND: return("Order not found");
- case ERR_TRADE_DEAL_NOT_FOUND: return("Deal not found");
- case ERR_TRADE_SEND_FAILED: return("Trade request sending failed");
- //--- Indicators
- case ERR_INDICATOR_UNKNOWN_SYMBOL: return("Unknown symbol");
- case ERR_INDICATOR_CANNOT_CREATE: return("Indicator cannot be created");
- case ERR_INDICATOR_NO_MEMORY: return("Not enough memory to add the indicator");
- case ERR_INDICATOR_CANNOT_APPLY: return("The indicator cannot be applied to another indicator");
- case ERR_INDICATOR_CANNOT_ADD: return("Error applying an indicator to chart");
- case ERR_INDICATOR_DATA_NOT_FOUND: return("Requested data not found");
- case ERR_INDICATOR_WRONG_HANDLE: return("Wrong indicator handle");
- case ERR_INDICATOR_WRONG_PARAMETERS: return("Wrong number of parameters when creating an indicator");
- case ERR_INDICATOR_PARAMETERS_MISSING: return("No parameters when creating an indicator");
- case ERR_INDICATOR_CUSTOM_NAME: return("The first parameter in the array must be the name of the custom indicator");
- case ERR_INDICATOR_PARAMETER_TYPE: return("Invalid parameter type in the array when creating an indicator");
- case ERR_INDICATOR_WRONG_INDEX: return("Wrong index of the requested indicator buffer");
- //--- Depth of Market
- case ERR_BOOKS_CANNOT_ADD: return("Depth Of Market can not be added");
- case ERR_BOOKS_CANNOT_DELETE: return("Depth Of Market can not be removed");
- case ERR_BOOKS_CANNOT_GET: return("The data from Depth Of Market can not be obtained");
- case ERR_BOOKS_CANNOT_SUBSCRIBE: return("Error in subscribing to receive new data from Depth Of Market");
- //--- File Operations
- case ERR_TOO_MANY_FILES: return("More than 64 files cannot be opened at the same time");
- case ERR_WRONG_FILENAME: return("Invalid file name");
- case ERR_TOO_LONG_FILENAME: return("Too long file name");
- case ERR_CANNOT_OPEN_FILE: return("File opening error");
- case ERR_FILE_CACHEBUFFER_ERROR: return("Not enough memory for cache to read");
- case ERR_CANNOT_DELETE_FILE: return("File deleting error");
- case ERR_INVALID_FILEHANDLE: return("A file with this handle was closed, or was not opening at all");
- case ERR_WRONG_FILEHANDLE: return("Wrong file handle");
- case ERR_FILE_NOTTOWRITE: return("The file must be opened for writing");
- case ERR_FILE_NOTTOREAD: return("The file must be opened for reading");
- case ERR_FILE_NOTBIN: return("The file must be opened as a binary one");
- case ERR_FILE_NOTTXT: return("The file must be opened as a text");
- case ERR_FILE_NOTTXTORCSV: return("The file must be opened as a text or CSV");
- case ERR_FILE_NOTCSV: return("The file must be opened as CSV");
- case ERR_FILE_READERROR: return("File reading error");
- case ERR_FILE_BINSTRINGSIZE: return("String size must be specified, because the file is opened as binary");
- case ERR_INCOMPATIBLE_FILE: return("A text file must be for string arrays, for other arrays - binary");
- case ERR_FILE_IS_DIRECTORY: return("This is not a file, this is a directory");
- case ERR_FILE_NOT_EXIST: return("File does not exist");
- case ERR_FILE_CANNOT_REWRITE: return("File can not be rewritten");
- case ERR_WRONG_DIRECTORYNAME: return("Wrong directory name");
- case ERR_DIRECTORY_NOT_EXIST: return("Directory does not exist");
- case ERR_FILE_ISNOT_DIRECTORY: return("This is a file, not a directory");
- case ERR_CANNOT_DELETE_DIRECTORY: return("The directory cannot be removed");
- case ERR_CANNOT_CLEAN_DIRECTORY: return("Failed to clear the directory (probably one or more files are blocked and removal operation failed)");
- case ERR_FILE_WRITEERROR: return("Failed to write a resource to a file");
- //--- String Casting
- case ERR_NO_STRING_DATE: return("No date in the string");
- case ERR_WRONG_STRING_DATE: return("Wrong date in the string");
- case ERR_WRONG_STRING_TIME: return("Wrong time in the string");
- case ERR_STRING_TIME_ERROR: return("Error converting string to date");
- case ERR_STRING_OUT_OF_MEMORY: return("Not enough memory for the string");
- case ERR_STRING_SMALL_LEN: return("The string length is less than expected");
- case ERR_STRING_TOO_BIGNUMBER: return("Too large number, more than ULONG_MAX");
- case ERR_WRONG_FORMATSTRING: return("Invalid format string");
- case ERR_TOO_MANY_FORMATTERS: return("Amount of format specifiers more than the parameters");
- case ERR_TOO_MANY_PARAMETERS: return("Amount of parameters more than the format specifiers");
- case ERR_WRONG_STRING_PARAMETER: return("Damaged parameter of string type");
- case ERR_STRINGPOS_OUTOFRANGE: return("Position outside the string");
- case ERR_STRING_ZEROADDED: return("0 added to the string end, a useless operation");
- case ERR_STRING_UNKNOWNTYPE: return("Unknown data type when converting to a string");
- case ERR_WRONG_STRING_OBJECT: return("Damaged string object");
- //--- Operations with Arrays
- case ERR_INCOMPATIBLE_ARRAYS: return("Copying incompatible arrays. String array can be copied only to a string array, and a numeric array - in numeric array only");
- case ERR_SMALL_ASSERIES_ARRAY: return("The receiving array is declared as AS_SERIES, and it is of insufficient size");
- case ERR_SMALL_ARRAY: return("Too small array, the starting position is outside the array");
- case ERR_ZEROSIZE_ARRAY: return("An array of zero length");
- case ERR_NUMBER_ARRAYS_ONLY: return("Must be a numeric array");
- case ERR_ONEDIM_ARRAYS_ONLY: return("Must be a one-dimensional array");
- case ERR_SERIES_ARRAY: return("Timeseries cannot be used");
- case ERR_DOUBLE_ARRAY_ONLY: return("Must be an array of type double");
- case ERR_FLOAT_ARRAY_ONLY: return("Must be an array of type float");
- case ERR_LONG_ARRAY_ONLY: return("Must be an array of type long");
- case ERR_INT_ARRAY_ONLY: return("Must be an array of type int");
- case ERR_SHORT_ARRAY_ONLY: return("Must be an array of type short");
- case ERR_CHAR_ARRAY_ONLY: return("Must be an array of type char");
- //--- Operations with OpenCL
- case ERR_OPENCL_NOT_SUPPORTED: return("OpenCL functions are not supported on this computer");
- case ERR_OPENCL_INTERNAL: return("Internal error occurred when running OpenCL");
- case ERR_OPENCL_INVALID_HANDLE: return("Invalid OpenCL handle");
- case ERR_OPENCL_CONTEXT_CREATE: return("Error creating the OpenCL context");
- case ERR_OPENCL_QUEUE_CREATE: return("Failed to create a run queue in OpenCL");
- case ERR_OPENCL_PROGRAM_CREATE: return("Error occurred when compiling an OpenCL program");
- case ERR_OPENCL_TOO_LONG_KERNEL_NAME: return("Too long kernel name (OpenCL kernel)");
- case ERR_OPENCL_KERNEL_CREATE: return("Error creating an OpenCL kernel");
- case ERR_OPENCL_SET_KERNEL_PARAMETER: return("Error occurred when setting parameters for the OpenCL kernel");
- case ERR_OPENCL_EXECUTE: return("OpenCL program runtime error");
- case ERR_OPENCL_WRONG_BUFFER_SIZE: return("Invalid size of the OpenCL buffer");
- case ERR_OPENCL_WRONG_BUFFER_OFFSET: return("Invalid offset in the OpenCL buffer");
- case ERR_OPENCL_BUFFER_CREATE: return("Failed to create and OpenCL buffer");
- //--- User-Defined Errors
- default: if(err_code>=ERR_USER_ERROR_FIRST && err_code<ERR_USER_ERROR_LAST)
- return("User error "+string(err_code-ERR_USER_ERROR_FIRST));
- }
- //---
- return("Unknown error");
- }
- //+------------------------------------------------------------------+
- double getATR(string symbol, int timeframe, int ma_period, int shift){
- string atrSymbol = correctSymbol(symbol);
- ENUM_TIMEFRAMES atrTimeframe = (timeframe == NULL || timeframe == 0) ? _Period : TFMigrate(timeframe);
- int handle = iATR(atrSymbol, atrTimeframe, ma_period);
- return(sqGetIndicatorValue(handle, 0, shift));
- }
- //+------------------------------------------------------------------+
- //+------------------------------------------------------------------+
- //+------------------------------------------------------------------+
- // ExitMethods includes
- //+------------------------------------------------------------------+
- //+------------------------------------------------------------------+
- void sqSetSLPT(long ticket, double sl, double pt){
- ZeroMemory(mrequest);
- if(PositionSelectByTicket(ticket)) {
- mrequest.position = ticket;
- mrequest.action = TRADE_ACTION_SLTP;
- mrequest.sl = sl != 0 ? sl : PositionGetDouble(POSITION_SL);
- mrequest.tp = pt != 0 ? pt : PositionGetDouble(POSITION_TP);
- }
- else if(OrderSelect(ticket)){
- mrequest.order = ticket;
- mrequest.action = TRADE_ACTION_MODIFY;
- mrequest.price = OrderGetDouble(ORDER_PRICE_OPEN);
- mrequest.sl = sl != 0 ? sl : OrderGetDouble(ORDER_SL);
- mrequest.tp = pt != 0 ? pt : OrderGetDouble(ORDER_TP);
- }
- else {
- Print(StringFormat("No order or position with ticket %d not found", ticket));
- }
- //--- setting request
- mrequest.symbol = PositionGetString(POSITION_SYMBOL);
- mrequest.magic = PositionGetInteger(POSITION_MAGIC);
- //--- action and return the result
- OrderSend(mrequest,mresult);
- }
- // Move Stop Loss to Break Even
- void sqManageSL2BE(int ticket) {
- if(!PositionSelectByTicket(ticket)){
- Verbose("Cannot select position with ticket ", ticket);
- return;
- }
- valueIdentificationSymbol = PositionGetString(POSITION_SYMBOL);
- double moveSLAtValue = sqGetValueByIdentification( sqGetMoveSL2BE(ticket) );
- if(moveSLAtValue > 0) {
- double newSL = 0;
- int error;
- int valueType = sqGetMoveSL2BEType(ticket);
- int orderType = PositionGetInteger(POSITION_TYPE);
- if(orderType == ORDER_TYPE_BUY || orderType == ORDER_TYPE_BUY_STOP || orderType == ORDER_TYPE_BUY_LIMIT) {
- if(valueType == SLPTTYPE_RANGE) {
- moveSLAtValue = sqGetBid(NULL) - moveSLAtValue;
- }
- } else {
- if(valueType == SLPTTYPE_RANGE) {
- moveSLAtValue = sqGetAsk(NULL) + moveSLAtValue;
- }
- }
- moveSLAtValue = NormalizeDouble(moveSLAtValue, _Digits);
- double addPips = sqGetValueByIdentification(sqGetSL2BEAddPips(ticket));
- double currentSL = PositionGetDouble(POSITION_SL);
- double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
- double takeProfit = PositionGetDouble(POSITION_TP);
- if(orderType == ORDER_TYPE_BUY) {
- newSL = openPrice + addPips;
- if (openPrice <= moveSLAtValue && (currentSL == 0 || currentSL < newSL) && !sqDoublesAreEqual(currentSL, newSL)) {
- Verbose("Moving SL 2 BE for order with ticket: ", ticket, " to :", newSL);
- if(!OrderModify(ticket, newSL, takeProfit)) {
- error = GetLastError();
- Verbose("Failed, error: ", error, " - ", ErrorDescription(error),", Ask: ", sqGetAsk(NULL), ", Bid: ", sqGetBid(NULL), " Current SL: ", currentSL);
- }
- }
- } else { // orderType == OP_SELL
- newSL = openPrice - addPips;
- if (openPrice >= moveSLAtValue && (currentSL == 0 || currentSL > newSL) && !sqDoublesAreEqual(currentSL, newSL)) {
- Verbose("Moving SL 2 BE for order with ticket: ", ticket, " to :", newSL);
- if(!OrderModify(ticket, newSL, takeProfit)) {
- error = GetLastError();
- Verbose("Failed, error: ", error, " - ", ErrorDescription(error),", Ask: ", sqGetAsk(NULL), ", Bid: ", sqGetBid(NULL), " Current SL: ", currentSL);
- }
- }
- }
- }
- }
- // Trailing Stop
- void sqManageTrailingStop(int ticket) {
- if(!PositionSelectByTicket(ticket)){
- Verbose("Cannot select position with ticket ", ticket);
- return;
- }
- valueIdentificationSymbol = PositionGetString(POSITION_SYMBOL);
- double tsValue = sqGetValueByIdentification( sqGetTrailingStop(ticket) );
- if(tsValue > 0) {
- double plValue;
- int error;
- int valueType = sqGetTrailingStopType(ticket);
- int orderType = PositionGetInteger(POSITION_TYPE);
- if(orderType == POSITION_TYPE_BUY) {
- if(valueType == SLPTTYPE_RANGE) {
- tsValue = sqGetBid(NULL) - tsValue;
- }
- } else {
- if(valueType == SLPTTYPE_RANGE) {
- tsValue = sqGetAsk(NULL) + tsValue;
- }
- }
- double tsActivation = sqGetValueByIdentification( sqGetTSActivation(ticket) );
- double currentSL = PositionGetDouble(POSITION_SL);
- double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
- double takeProfit = PositionGetDouble(POSITION_TP);
- if(orderType == POSITION_TYPE_BUY) {
- plValue = sqGetBid(NULL) - openPrice;
- if (plValue >= tsActivation && (currentSL == 0 || currentSL < tsValue) && !sqDoublesAreEqual(currentSL, tsValue)) {
- Verbose("Moving trailing stop for order with ticket: ", ticket, " to :", tsValue);
- if(!OrderModify(ticket, tsValue, takeProfit)) {
- error = GetLastError();
- Verbose("Failed, error: ", error, " - ", ErrorDescription(error),", Ask: ", sqGetAsk(NULL), ", Bid: ", sqGetBid(NULL), " Current SL: ", currentSL);
- }
- }
- } else { // orderType == OP_SELL
- plValue = openPrice - sqGetAsk(NULL);
- if (plValue >= tsActivation && (currentSL == 0 || currentSL > tsValue) && !sqDoublesAreEqual(currentSL, tsValue)) {
- Verbose("Moving trailing stop for order with ticket: ", ticket, " to :", tsValue);
- if(!OrderModify(ticket, tsValue, takeProfit)) {
- error = GetLastError();
- Verbose("Failed, error: ", error, " - ", ErrorDescription(error),", Ask: ", sqGetAsk(NULL), ", Bid: ", sqGetBid(NULL), " Current SL: ", currentSL);
- }
- }
- }
- }
- }
- void sqManageExitAfterXBars(int ticket) {
- if(!PositionSelectByTicket(ticket)){
- Verbose("Exit after bars - Cannot select position with ticket ", ticket);
- return;
- }
- int exitBars = sqGetExitAfterXBars(ticket);
- if(exitBars > 0) {
- if (sqGetOpenBarsForOrder(exitBars+10, PositionGetInteger(POSITION_TIME)) >= exitBars) {
- Verbose("Exit After ", exitBars, " bars - closing order with ticket: ", ticket);
- if(!sqClosePositionAtMarket(ticket)){
- Verbose("Closing position failed, error: ", GetLastError(), " - ", ErrorDescription(GetLastError()));
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement