Second(s) timeframes on your MT4

 

this script converts the chart's ticks into any Second(s)timeframes !!!

the Script works only for XAUUSD, you can modify it to work with other pairs or other names of Gold pair.

Example custom periods:

S5
S10
S15
S20
S30
S45

S50

Once the Second(s) chart is generated, you can apply almost everything you normally use on regular charts:

✅ Templates ( .tpl )
✅ Indicators
Expert Advisors
✅ Objects & drawings
✅ Trendlines
✅ Fibonacci tools
✅ Moving averages
✅ Oscillators
✅ Custom indicators
✅ Price action tools


Enjoy the Script !!

//+------------------------------------------------------------------+
//|                                             XAUUSD_Seconds.mq4   |
//|                        Custom Seconds Offline Chart Generator    |
//|                        For MT4 Build 600+                        |
//+------------------------------------------------------------------+
#property strict
#property show_inputs

input int   InpSecondsPeriod = 10;      // Seconds timeframe
input bool  InpAutoOpenChart = true;    // Auto open offline chart
input bool  InpShowComment   = true;    // Show status comment

int      ExtHandle      = -1;
long     OfflineChartID = 0;
int      OfflinePeriod  = 20000;

datetime CurrentBarTime = 0;

MqlRates Rate;

string OfflineFileName;

//+------------------------------------------------------------------+
//| Script start                                                     |
//+------------------------------------------------------------------+
void OnStart()
{
   if(Symbol() != "XAUUSD")
   {
      Alert("Attach this script to XAUUSD only.");
      return;
   }

   if(InpSecondsPeriod < 1)
   {
      Alert("Seconds period must be >= 1");
      return;
   }

   OfflinePeriod += InpSecondsPeriod;

   OfflineFileName = Symbol() + (string)OfflinePeriod + ".hst";

   ExtHandle = FileOpenHistory(
      OfflineFileName,
      FILE_BIN|FILE_WRITE|FILE_SHARE_WRITE|FILE_SHARE_READ
   );

   if(ExtHandle < 0)
   {
      Alert("Failed to create offline history file.");
      return;
   }

   WriteHistoryHeader();

   WaitForFirstTick();

   BuildInitialBar();

   if(InpAutoOpenChart)
   {
      OpenOfflineChart();
   }

   MainLoop();
}

//+------------------------------------------------------------------+
//| Wait for first market tick                                       |
//+------------------------------------------------------------------+
void WaitForFirstTick()
{
   while(!IsStopped())
   {
      if(RefreshRates())
      {
         if(TimeCurrent() > 0)
            break;
      }

      Sleep(100);
   }
}

//+------------------------------------------------------------------+
//| Build first candle                                               |
//+------------------------------------------------------------------+
void BuildInitialBar()
{
   datetime now = TimeCurrent();

   CurrentBarTime = NormalizeSecondTime(now);

   Rate.time         = CurrentBarTime;
   Rate.open         = Bid;
   Rate.high         = Bid;
   Rate.low          = Bid;
   Rate.close        = Bid;
   Rate.tick_volume  = 1;
   Rate.spread       = MarketInfo(Symbol(), MODE_SPREAD);
   Rate.real_volume  = 0;

   FileWriteStruct(ExtHandle, Rate);
   FileFlush(ExtHandle);
}

//+------------------------------------------------------------------+
//| Main processing loop                                             |
//+------------------------------------------------------------------+
void MainLoop()
{
   datetime last_refresh = 0;

   while(!IsStopped())
   {
      RefreshRates();

      datetime now = TimeCurrent();

      datetime normalized = NormalizeSecondTime(now);

      if(normalized > CurrentBarTime)
      {
         FinalizeCurrentBar();

         StartNewBar(normalized);
      }
      else
      {
         UpdateCurrentBar();
      }

      if(InpShowComment)
      {
         Comment(
            "XAUUSD Seconds Chart Generator\n",
            "Seconds TF : S", InpSecondsPeriod, "\n",
            "Offline ID : ", OfflinePeriod, "\n",
            "Status     : RUNNING\n",
            "Bid        : ", DoubleToString(Bid, Digits)
         );
      }

      if(TimeLocal() - last_refresh >= 2)
      {
         RefreshOfflineChart();
         last_refresh = TimeLocal();
      }

      Sleep(20);
   }

   Comment("");
}

//+------------------------------------------------------------------+
//| Start new candle                                                 |
//+------------------------------------------------------------------+
void StartNewBar(datetime bar_time)
{
   CurrentBarTime = bar_time;

   Rate.time         = CurrentBarTime;
   Rate.open         = Bid;
   Rate.high         = Bid;
   Rate.low          = Bid;
   Rate.close        = Bid;
   Rate.tick_volume  = 1;
   Rate.spread       = MarketInfo(Symbol(), MODE_SPREAD);
   Rate.real_volume  = 0;

   FileWriteStruct(ExtHandle, Rate);
   FileFlush(ExtHandle);
}

//+------------------------------------------------------------------+
//| Update current candle                                            |
//+------------------------------------------------------------------+
void UpdateCurrentBar()
{
   if(Bid > Rate.high)
      Rate.high = Bid;

   if(Bid < Rate.low)
      Rate.low = Bid;

   Rate.close = Bid;

   Rate.tick_volume++;

   int struct_size = sizeof(MqlRates);

   FileSeek(ExtHandle, -struct_size, SEEK_END);

   FileWriteStruct(ExtHandle, Rate);

   FileFlush(ExtHandle);
}

//+------------------------------------------------------------------+
//| Finalize candle                                                  |
//+------------------------------------------------------------------+
void FinalizeCurrentBar()
{
   int struct_size = sizeof(MqlRates);

   FileSeek(ExtHandle, -struct_size, SEEK_END);

   FileWriteStruct(ExtHandle, Rate);

   FileFlush(ExtHandle);
}

//+------------------------------------------------------------------+
//| Normalize time                                                   |
//+------------------------------------------------------------------+
datetime NormalizeSecondTime(datetime t)
{
   return (t / InpSecondsPeriod) * InpSecondsPeriod;
}

//+------------------------------------------------------------------+
//| Write HST header                                                 |
//+------------------------------------------------------------------+
void WriteHistoryHeader()
{
   int    version = 401;
   string copyright;
   string symbol = Symbol();
   int    period = OfflinePeriod;
   int    digits = Digits;
   int    unused[13];

   ArrayInitialize(unused, 0);

   copyright = "Custom Seconds Chart";

   FileWriteInteger(ExtHandle, version, LONG_VALUE);
   FileWriteString(ExtHandle, copyright, 64);
   FileWriteString(ExtHandle, symbol, 12);
   FileWriteInteger(ExtHandle, period, LONG_VALUE);
   FileWriteInteger(ExtHandle, digits, LONG_VALUE);
   FileWriteInteger(ExtHandle, 0, LONG_VALUE);
   FileWriteInteger(ExtHandle, 0, LONG_VALUE);

   FileWriteArray(ExtHandle, unused, 0, 13);
}

//+------------------------------------------------------------------+
//| Open offline chart                                               |
//+------------------------------------------------------------------+
void OpenOfflineChart()
{
   OfflineChartID = ChartOpen(Symbol(), OfflinePeriod);

   Sleep(1000);

   RefreshOfflineChart();
}

//+------------------------------------------------------------------+
//| Refresh chart                                                    |
//+------------------------------------------------------------------+
void RefreshOfflineChart()
{
   if(OfflineChartID <= 0)
      return;

   ChartSetSymbolPeriod(
      OfflineChartID,
      Symbol(),
      OfflinePeriod
   );

   ChartRedraw(OfflineChartID);
}

//+------------------------------------------------------------------+
//| Cleanup                                                          |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   Comment("");

   if(ExtHandle >= 0)
   {
      FileClose(ExtHandle);
      ExtHandle = -1;
   }
}
//+------------------------------------------------------------------+
 
Ynal Al Khalil:


The forum is for mostly questions regarding the use of mt4 and mt5 AND the reporting of program bugs. I suggest that you place this on codebase since your post is not in response to either of these.

your post is obviously fishing for sales. if i understand the sellers agreement that you and I both agreed to when we applied for seller status, we cannnot post on the forum unless our posts are is in response to either of the above.

 
Michael Charles Schefe #:

The forum is for mostly questions regarding the use of mt4 and mt5 AND the reporting of program bugs. I suggest that you place this on codebase since your post is not in response to either of these.

your post is obviously fishing for sales. if i understand the sellers agreement that you and I both agreed to when we applied for seller status, we cannnot post on the forum unless our posts are is in response to either of the above.

what ??!!!!
 
Ynal Al Khalil #:
what ??!!!!

In my experience, it's a lot easier to search for/find a CodeBase Publication than an individual Forum thread. Why not post it in the CodeBase and then watch the count of views and downloads climb?

In this way, you can help more traders and legitimately increase your user rating faster.

By the way, is there a reason that your file name and code comment are limited to XAUUSD?

 
Ryan L Johnson #:

In my experience, it's a lot easier to search for/find a CodeBase Publication than an individual Forum thread. Why not post it in the CodeBase and then watch the count of views and downloads climb?

In this way, you can help more traders and legitimately increase your user rating faster.

By the way, is there a reason that your file name and code comment are limited to XAUUSD?

I already tried to post this in the CodeBase, 
they  didn't publish them !!
I don't know why, 
the same with another post (Unlimited MT5 trades copier using two Python scripts)
 
Ynal Al Khalil #:
I already tried to post this in the CodeBase, 
they  didn't publish them !!
I don't know why, 
the same with another post (Unlimited MT5 trades copier using two Python scripts)

Likely due to the incorporation of an external file─same as the Market validator. My bad, for not seeing that in your code previously.

FYI, you can post it in the Blog section of your user Profile too which is relatively unrestriced.

 
Hello, I came across your post on FXBlue and wanted to express my sincere thanks. However, the script currently only works with XAUUSD; could you "unlock" and rewrite the source code so it works with all instruments? For instance, I trade gold on an Exness Zero account where the symbol is XAUUSDz rather than XAUUSD (without the 'z' suffix). Please rewrite it. Also, if possible, could you create versions for both MT4 and MT5? Thank you very much.
 
hong phuc #:
Hello, I came across your post on FXBlue and wanted to express my sincere thanks. However, the script currently only works with XAUUSD; could you "unlock" and rewrite the source code so it works with all instruments? For instance, I trade gold on an Exness Zero account where the symbol is XAUUSDz rather than XAUUSD (without the 'z' suffix). Please rewrite it. Also, if possible, could you create versions for both MT4 and MT5? Thank you very much.
till the end of this week, I'll make the modifications you requested.
It is a piece of cake !!!
 
hong phuc #:
Hello, I came across your post on FXBlue and wanted to express my sincere thanks. However, the script currently only works with XAUUSD; could you "unlock" and rewrite the source code so it works with all instruments? For instance, I trade gold on an Exness Zero account where the symbol is XAUUSDz rather than XAUUSD (without the 'z' suffix). Please rewrite it. Also, if possible, could you create versions for both MT4 and MT5? Thank you very much.

Just delete:

   if(Symbol() != "XAUUSD")
   {
      Alert("Attach this script to XAUUSD only.");
      return;
   }

and replace:

            "XAUUSD Seconds Chart Generator\n",

with:

            Symbol(), " Seconds Chart Generator\n",

Because Symbol() is used throughout the rest of the code. It wasn't really hardcoded for XAUUSD.

 
Michael Charles Schefe #:

The forum is for mostly questions regarding the use of mt4 and mt5 AND the reporting of program bugs. I suggest that you place this on codebase since your post is not in response to either of these.

your post is obviously fishing for sales. if i understand the sellers agreement that you and I both agreed to when we applied for seller status, we cannnot post on the forum unless our posts are is in response to either of the above.

The on-point rule is Rule #16 of the Rules of Using the Market Service:

"16. The Seller shall not use spam to promote Products on the Market both on www.mql5.com website and via third-party services. Upon detection of spam, the Seller's account will be blocked and all his or her Products will be removed from the Market."

Having quoted that, it would be rather self-defeating for a Seller to post the source code of her/his Market product in promotion thereof. That is to say, who would rent/buy an ex5 file when its mq5 file is free? I should note that I didn't inspect any FXBlue content for potential spam. FXBlue certainly is a third-party service but again, if nothing is for sale, no Market product exists─the Rule doesn't apply.

On a related note, there is a more general rule against self-promotion, e.g., a Seller posting a profitable backtest report. In contrast thereto, posting a simple script is merely giving away a utility.

 
Ryan L Johnson #:

The on-point rule is Rule #16 of the Rules of Using the Market Service:

"16. The Seller shall not use spam to promote Products on the Market both on www.mql5.com website and via third-party services. Upon detection of spam, the Seller's account will be blocked and all his or her Products will be removed from the Market."

Having quoted that, it would be rather self-defeating for a Seller to post the source code of her/his Market product in promotion thereof. That is to say, who would rent/buy an ex5 file when its mq5 file is free? I should note that I didn't inspect any FXBlue content for potential spam. FXBlue certainly is a third-party service but again, if nothing is for sale, no Market product exists─the Rule doesn't apply.

On a related note, there is a more general rule against self-promotion, e.g., a Seller posting a profitable backtest report. In contrast thereto, posting a simple script is merely giving away a utility.

so ?????
did I make any mistake ???