Spread between two futures

 

Good afternoon everyone!

I have written an indicator that draws the spread between two futures. I have two problems:

1) the indicator is wildly glitchy, sometimes it is displayed, sometimes it is not displayed, then it shows some nonsense (I have to press refresh, and then it seems to fall into place);

2) The author's algorithm for synchronizing prices of two futures: because futures may often lack some or other bars (due to low liquidity), then there was a problem to synchronize their bars to get a real spread between them. I searched on the forum and did not find anything on this subject. Finally, I came up with the following method: we take 4 time series - bar time for instrument #1, bar closing prices of instrument #1, bar time of instrument #2, bar closing price of instrument #2. If we specify the same number of bars in the timeseries, they will be identical for one instrument and identical for another one (binding time and close prices). It only remains to synchronize the time of one instrument relative to the other. Below is an example of spread building on the basis of data of instrument #1: we take the i-th closing price of instrument #1 and subtract from it the price of instrument #2 whose index is equal to the time array index of instrument #2 whose time value coincided with the array for instrument #1.

   if(Flag==SincForIn1)									// Синхронизируем по первому инструменту.
      {
       while(i>=0)                                                			// Цикл перебора для расчета спреда для всех непосчитанных баров, от самого последнего i до нулевого.
         {
          SpreadBuffer[i]=closeIn1[i]-closeIn2[ArrayBsearch(timeIn2,timeIn1[i])]; 	// Расчет спреда (существуют различия в количесве баров двух инструментов, за основу берутся бары Инструмента №1)
          i--;                                                    			// Снижение индекса бара для перехода расчетов к следующему бару и так до нулевого включительно.
         }

I cannot think of anything better. I would like to listen to your suggestions, maybe there is a much more simple, clear and effective way to build a synchronized spreads chart of two futures. Maybe it will stop glitching then, or maybe I write "cool" indicators...

I attached the indicator to the post.

Thanks in advance.

Files:
Spread.mq5  24 kb
 
iiivasyaiii:

Good afternoon everyone!

I have written an indicator that draws the spread between two futures. I have two problems:

1) the indicator is wildly glitchy, sometimes it is displayed, sometimes it is not displayed, then it shows some nonsense (I have to press refresh, and then it seems to fall into place);

2) The author's algorithm for synchronizing prices of two futures: because futures may often lack some or other bars (due to low liquidity), then there was a problem to synchronize their bars to get a real spread between them. I searched on the forum and did not find anything on this subject. Finally, I have thought of the following method: we take 4 time series - bar time for instrument #1, bar close prices of instrument #1, bar time of instrument #2, bar close prices of instrument #2. If we specify the same number of bars in the timeseries, they will be identical for one instrument and identical for another one (binding time and close prices). It only remains to synchronize the time of one instrument relative to the other. Below is an example of spread building on the basis of data of instrument #1: we take the i-th closing price of instrument #1 and subtract from it the price of instrument #2 whose index is equal to the time array index of instrument #2 whose time value coincided with the array for instrument #1.

I cannot think of anything better. I would like to listen to your suggestions, maybe there is a much more simple, clear and effective way to build a synchronized spreads chart of two futures. Maybe it will stop glitching then, or maybe I write "cool" indicators...

I attached the indicator to the post.

Thanks in advance.

You have to take bid and ask prices to plot the spread. The chart is drawn by flipper and that would not be correct.
 
Maxim Romanov:
I need to take the bid and ask prices to build the spread. The chart is drawn by flipper and this will not be correct.

Maxim, thank you for your attention to my problem.

I have a couple of comments to your answer:

1) Prices of transactions that have occurred (last) are not drawn, this is not forex. If you meant something else, please explain in more detail.

2) Bid and ask is certainly good, but it's an order of magnitude more complicated. Tried to write two additional lines on them for the main spread, like buy spread and sell spread. I tried it once (by the way it was drawn for a long time), but then I changed something in the code and it disappeared and never reappeared))) If you want, I can send you his code. And the main drawback of bid and ax: if I remember, the data bid and ax are stored for the last 2000 ticks, so a long history on it can not be analyzed.

So please, let' s start with building the spread between the two instruments on the closing prices. Is my approach to synchronize prices of two instruments using ArrayBsearch() correct or is there a simpler method?

 
iiivasyaiii:

Maxim, thank you for your attention to my problem.

I have a couple of comments to your answer:

1) Prices of transactions that occurred (last) are not drawn, this is not forex.

With such knowledge it is too early for you to write such indicators.

 
iiivasyaiii:

Good afternoon everyone!

I have written an indicator that draws the spread between two futures. I have two problems:

1) the indicator is wildly glitchy, sometimes it is displayed, sometimes it is not displayed, then it shows some nonsense (I have to press refresh, and then it seems to fall into place);

2) The author's algorithm for synchronizing prices of two futures: because futures may often lack some or other bars (due to low liquidity), then there was a problem to synchronize their bars to get a real spread between them. I searched on the forum and did not find anything on this subject. Finally, I have thought of the following method: we take 4 time series - bar time for instrument #1, bar close prices of instrument #1, bar time of instrument #2, bar close prices of instrument #2. If we specify the same number of bars in the timeseries, they will be identical for one instrument and identical for another one (binding time and close prices). It only remains to synchronize the time of one instrument relative to the other. Below is an example of spread forming based on the data of instrument #1: we take the i-th closing price of instrument #1 and subtract from it the price of instrument #2 whose index is equal to the time array index of instrument #2 whose time value coincided with the array for instrument #1.

I cannot think of anything better. I would like to listen to your suggestions, maybe there is a much more simple, clear and effective way to build a synchronized spreads chart of two futures. Maybe it will stop glitching then, or maybe I write "cool" indicators...

I attached the indicator to the post.

I have attached it to the post. Thank you in advance.

Good day!

1. You have to write in the "Stock Trading" section.

2. You cannot synchronize 2 futures by bars.

You should take as a basis the bars of one of the futures (the most liquid SBRF 9.20 is better).

3. For a complete picture of the spread, you should take not close, but ticks and synchronize them with the bars of one selected as the main futures.

4. To recalculate quickly, you should memorize the last calculated position.

Example of code for spread recalculation with bar time synchronization

int pr_pos = 0;
            int sec_pos = 0;
            bool is_found;
            int pr_mem = 0;
            int sec_mem = 0;
            for(int i = 0; i < a_bars; i++)
            {
              is_found = false;
              while(pr_pos < pr_cnt) 
              {
                if((ulong(data_time[i].time) <= ulong(pr_ticks[pr_pos].time)) &&
                   (ulong(data_time[i].time) + 60 > ulong(pr_ticks[pr_pos].time)))
                {
                  pr_mem = pr_pos;
                  while(sec_pos < sec_cnt) 
                  {
                    if((ulong(data_time[i].time) <= ulong(sec_ticks[sec_pos].time)) &&
                       (ulong(data_time[i].time) + 60 > ulong(sec_ticks[sec_pos].time)))
                    {
                      is_found = true;
                      sec_mem = sec_pos;
                      if((sec_ticks[sec_pos].bid > 0.0) && (pr_ticks[pr_pos].ask > 0.0) &&
                         (sec_ticks[sec_pos].ask > 0.0) && (pr_ticks[pr_pos].bid > 0.0))
                      {
                        data_time[i].hi_value = sec_ticks[sec_pos].bid - pr_ticks[pr_pos].ask;
                        data_time[i].low_value = sec_ticks[sec_pos].ask - pr_ticks[pr_pos].bid;
                      }
                      break;
                    }
                    sec_pos++;
                  }
                  break;
                }
                pr_pos++;
              }
              if(is_found == false)
              {
                pr_pos = pr_mem;
                sec_pos = sec_mem;
              }
            }
 
Alexey Viktorov:

With that kind of knowledge, it's a little early for you to be writing such indicators.

Since you are so smart, maybe you can tell me how to synchronise two price series by closing prices;)

 
prostotrader:

Good afternoon!

1. You need to write to the "Exchange Trading" section.

2. It is not possible to synchronize 2 futures by bars.

You should take as a basis the bars of one of the futures (the most liquid SBRF 9.20 is better).

3. For a complete picture of the spread, you should take not close, but ticks and synchronize them with the bars of one selected as the main futures.

4. To recalculate quickly, you should memorize the last calculated position.

An example of code of spread recalculation with bar time synchronization

Prostotrader, thank you very much for the tip! Interesting solution, I will try it now and report back later.

 
iiivasyaiii:

Since you are so smart, maybe you can tell me how to synchronise two price series by closing prices;)

You have already been told the essence of the question. You cannot build a spread by deal prices (let alone closing prices!), because there may not be any deals in the slow leg for a long time, and even if there are, they will be unsynchronized with the prices of deals of the fast leg. I.e. the value of such information is zero. There are always (or almost always) current bid and ask prices in the market, and it is them that should be analyzed.

 
iiivasyaiii:

Maxim, thank you for your attention to my problem.

I have a couple of comments to your answer:

1) Prices of transactions that have occurred (last) are not drawn, this is not forex. If you meant something else, please explain in more detail.

2) Bid and ask is certainly good, but it's an order of magnitude more complicated. Tried to write two additional lines on them for the main spread, like buy spread and sell spread. I tried it once (by the way it was drawn that way for a long time), but then I changed something in the code and it disappeared and never reappeared)), if I need it, I can send you his code. And the main drawback of bid and ax: if I remember, the data bid and ax are stored for the last 2000 ticks, so a long history on it can not be analyzed.

So please, let' s start with building the spread between the two instruments on the closing prices. Is my approach to synchronize prices of two instruments using ArrayBsearch() correct or is there a simpler method?

I'm not a programmer, I don't need the code, I can't help with the codes. But I will give you a tip in essence. So, the exchange instruments are built by the price in the terminal and, as prostotrader wrote, it's not correct to synchronize them by close prices. By ticks, yes, it will be correct. Look for the right way at once, why make a mistake.)
 
prostotrader:

Good afternoon!

1. You need to write to the "Exchange Trading" section.

2. It is not possible to synchronize 2 futures by bars.

You should take as a basis the bars of one of the futures (the most liquid SBRF 9.20 is better).

3. For a complete picture of the spread, you should take not close, but ticks and synchronize them with the bars of one selected as the main futures.

4. To recalculate quickly, you should memorize the last calculated position.

An example of code of spread recalculation with bar time synchronization

Prostotrader, good day! Please advise me, I did not quite understand your code:

1) Did you use the CopyTicksRange or CopyTicks function?

2) The description of these functions says that they can copy no more than 2000 ticks, it means that this indicator cannot analyze longer history?

 
Dmi3:

You have already been told the essence of the question. The spread cannot be based on deal prices (let alone closing prices!), because there may not be any deals in the slow leg for a long time and, even if there are, they will be out of sync with the deal prices of the fast leg. I.e. the value of such information is zero. There are always (or almost always) actual bid and ask prices in the market, and it is them that we must analyze.

I'm not disputing that bids are more accurate (though when I had a short time indicator showing three spreads: flipper, ask-bead and bid-ask, flipper most of the time went between the last two, which shows that in general the flipper spread on liquid instruments is adequate).

Let's then figure out how to do the asc/bid synchronization in the least resource intensive way possible and preferably with a deep history.

For example, Prostatrader offers an interesting option (above).