
// Info.mq5

#property indicator_chart_window

#include <WinAPI\winapi.mqh>

struct Info
{
	MqlTick tick;
};

struct Dom
{
	uint number;
};

#import "msvcrt.dll"
	int memcpy(PVOID, Info&, uint);
	int memcpy(PVOID, Dom&, uint);
	int memcpy(PVOID, MqlBookInfo&, uint);
#import

MqlBookInfo book[];

#define BUFSIZE                 1024*1024
#define INVALID_HANDLE_VALUE    -1
#define PAGE_READWRITE          4
#define FILE_MAP_ALL_ACCESS     983071
#define WM_APP                  0x8000
#define PM_DOM                  0x80FF

HANDLE hmapfile = 0;
PVOID file = 0;
Info info;
HANDLE target;
const string window_name = "MyApp";
const string shared_mem_name = "smo";

int OnInit()
{
   hmapfile = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, BUFSIZE, shared_mem_name);
   if(hmapfile != NULL)
   {
      file = MapViewOfFile(hmapfile, FILE_MAP_ALL_ACCESS, 0, 0, BUFSIZE);
      if(file != NULL)
      {
         MarketBookAdd(_Symbol);
         return INIT_SUCCEEDED;
      }
      CloseHandle(hmapfile);
   }
   return INIT_FAILED;
}

void OnDeinit(const int reason)
{
   UnmapViewOfFile(file);
   CloseHandle(hmapfile);
   MarketBookRelease(_Symbol);
}

int OnCalculate(const int rates_total, const int prev_calculated, const int begin, const double &price[])
{
   target = FindWindowW(NULL, window_name);
   if(target != 0)
   {
      SymbolInfoTick(_Symbol, info.tick);
      memcpy(file, info, sizeof(Info));
      PostMessageW(target, WM_APP, 0, 0);
   }
   return rates_total;
}

void OnBookEvent(const string &symbol)
{
	if(symbol == _Symbol)
	{
		target = FindWindowW(NULL, window_name);
		if(target != 0)
		{
			MarketBookGet(symbol, book);
			int booksize = ArraySize(book);
			Dom dom;
			dom.number = booksize;
			memcpy(file+1024, dom, sizeof(Dom));
			memcpy(file+1024+sizeof(Dom), book[0], booksize * sizeof(MqlBookInfo));
			PostMessageW(target, PM_DOM, 0, 0);
			return;
		}
	}
}
