//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
MqlTick ticks[];
//--- registrando la hora de inicio antes de recibir los ticks
uint start=GetTickCount();
//--- solicitando la historia de ticks de un día
ulong to=TimeCurrent()*1000;
ulong from=to-PeriodSeconds(PERIOD_D1)*1000;
if(CopyTicksRange(_Symbol, ticks, COPY_TICKS_ALL, from, to)==-1)
{
PrintFormat("%s: CopyTicksRange(%s - %s) failed, error=%d",
_Symbol, TimeToString(datetime(from/1000)), TimeToString(datetime(to/1000)), _LastError);
return;
}
else
{
//--- cuántos ticks y en qué tiempo los hemos obtenido
PrintFormat("%s: CopyTicksRange received %d ticks in %d ms (from %s to %s)",
_Symbol, ArraySize(ticks), GetTickCount()-start,
TimeToString(datetime(from/1000)), TimeToString(datetime(to/1000)));
}
//--- comparando el nombre del archivo para guardar la base de datos
string filename=_Symbol+" "+TimeToString(datetime(from/1000))+" - "+TimeToString(datetime(to/1000))+".sqlite";
StringReplace(filename, ":", "."); // el símbolo ":" está prohibido en los nombres de los archivos
//--- abrimos/creamos la base de datos en la carpeta general de los terminales
int db=DatabaseOpen(filename, DATABASE_OPEN_READWRITE | DATABASE_OPEN_CREATE | DATABASE_OPEN_COMMON);
if(db==INVALID_HANDLE)
{
Print("Database: ", filename, " open failed with code ", GetLastError());
return;
}
else
Print("Database: ", filename, " opened successfully");
//--- creando el recuadro TICKS
if(!DatabaseExecute(db, "CREATE TABLE TICKS("
"SYMBOL CHAR(10),"
"TIME INT NOT NULL,"
"BID REAL,"
"ASK REAL,"
"LAST REAL,"
"VOLUME INT,"
"TIME_MSC INT,"
"VOLUME_REAL REAL);"))
{
Print("DB: ", filename, " create table TICKS failed with code ", GetLastError());
DatabaseClose(db);
return;
}
//--- mostrando la lista de todos los campos en el recuadro TICKS
if(DatabasePrint(db, "PRAGMA TABLE_INFO(TICKS)", 0)<0)
{
PrintFormat("DatabasePrint(\"PRAGMA TABLE_INFO(TICKS)\") failed, error code=%d at line %d", GetLastError(), __LINE__);
DatabaseClose(db);
return;
}
//--- creando una solicitud parametrizada de adición de ticks al recuadro TICKS
string sql="INSERT INTO TICKS (SYMBOL,TIME,BID,ASK,LAST,VOLUME,TIME_MSC,VOLUME_REAL)"
" VALUES (?1,?2,?3,?4,?5,?6,?7,?8)"; // parámetros de la solicitud
int request=DatabasePrepare(db, sql);
if(request==INVALID_HANDLE)
{
PrintFormat("DatabasePrepare() failed with code=%d", GetLastError());
Print("SQL request: ", sql);
DatabaseClose(db);
return;
}
//--- estableciendo el valor del primer parámetro de la solicitud
DatabaseBind(request, 0, _Symbol);
//--- rellenando la hora de comienzo antes de añadir los ticks al recuadro TICKS
start=GetTickCount();
DatabaseTransactionBegin(db);
int total=ArraySize(ticks);
bool request_error=false;
for(int i=0; i<total; i++)
{
//--- estableciendo los valores del resto de parámetros antes de añadir la entrada
ResetLastError();
if(!DatabaseBind(request, 1, ticks[i].time))
{
PrintFormat("DatabaseBind() failed with code=%d", GetLastError());
PrintFormat("Tick #%d line=%d", i+1, __LINE__);
request_error=true;
break;
}
//--- si la anterior llamada de DatabaseBind() ha tenido éxito, establecemos el siguiente parámetro
if(!request_error && !DatabaseBind(request, 2, ticks[i].bid))
{
PrintFormat("DatabaseBind() failed with code=%d", GetLastError());
PrintFormat("Tick #%d line=%d", i+1, __LINE__);
request_error=true;
break;
}
if(!request_error && !DatabaseBind(request, 3, ticks[i].ask))
{
PrintFormat("DatabaseBind() failed with code=%d", GetLastError());
PrintFormat("Tick #%d line=%d", i+1, __LINE__);
request_error=true;
break;
}
if(!request_error && !DatabaseBind(request, 4, ticks[i].last))
{
PrintFormat("DatabaseBind() failed with code=%d", GetLastError());
PrintFormat("Tick #%d line=%d", i+1, __LINE__);
request_error=true;
break;
}
if(!request_error && !DatabaseBind(request, 5, ticks[i].volume))
{
PrintFormat("DatabaseBind() failed with code=%d", GetLastError());
PrintFormat("Tick #%d line=%d", i+1, __LINE__);
request_error=true;
break;
}
if(!request_error && !DatabaseBind(request, 6, ticks[i].time_msc))
{
PrintFormat("DatabaseBind() failed with code=%d", GetLastError());
PrintFormat("Tick #%d line=%d", i+1, __LINE__);
request_error=true;
break;
}
if(!request_error && !DatabaseBind(request, 7, ticks[i].volume_real))
{
PrintFormat("DatabaseBind() failed with code=%d", GetLastError());
PrintFormat("Tick #%d line=%d", i+1, __LINE__);
request_error=true;
break;
}
//--- ejecutando la solicitud de inserción de una entrada y comprobando si es errónea
if(!request_error && !DatabaseRead(request) && (GetLastError()!=ERR_DATABASE_NO_MORE_DATA))
{
PrintFormat("DatabaseRead() failed with code=%d", GetLastError());
DatabaseFinalize(request);
request_error=true;
break;
}
//--- reseteando la solicitud a su estado inicial antes de la siguiente actualización de parámetros
if(!request_error && !DatabaseReset(request))
{
PrintFormat("DatabaseReset() failed with code=%d", GetLastError());
DatabaseFinalize(request);
request_error=true;
break;
}
} //--- ya hemos finalizado, se ha pasado por todos los ticks
//--- ¿cómo han salido las transacciones?
if(request_error)
{
PrintFormat("Table TICKS: failed to add %d ticks ", ArraySize(ticks));
DatabaseTransactionRollback(db);
DatabaseClose(db);
return;
}
else
{
DatabaseTransactionCommit(db);
PrintFormat("Table TICKS: added %d ticks in %d ms",
ArraySize(ticks), GetTickCount()-start);
}
//--- cerramos el archivo con la base de datos y comunicamos este hecho
DatabaseClose(db);
PrintFormat("Database: %s created and closed", filename);
}
/*
Resultado:
EURUSD: CopyTicksRange received 268061 ticks in 47 ms (from 2020.03.18 12:40 to 2020.03.19 12:40)
Database: EURUSD 2020.03.18 12.40 - 2020.03.19 12.40.sqlite opened successfully
#| cid name type notnull dflt_value pk
-+-----------------------------------------------
1| 0 SYMBOL CHAR(10) 0 0
2| 1 TIME INT 1 0
3| 2 BID REAL 0 0
4| 3 ASK REAL 0 0
5| 4 LAST REAL 0 0
6| 5 VOLUME INT 0 0
7| 6 TIME_MSC INT 0 0
8| 7 VOLUME_REAL REAL 0 0
Table TICKS: added 268061 ticks in 797 ms
Database: EURUSD 2020.03.18 12.40 - 2020.03.19 12.40.sqlite created and closed
OnCalculateCorrelation=0.87 2020.03.19 13:00: EURUSD vs GBPUSD PERIOD_M30
*/
|