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.