void CDatabaseFrames::OnTesterDeinit(void)
{
//--- возьмем имя советника и время окончания оптимизации
string filename=MQLInfoString(MQL_PROGRAM_NAME)+" "+TimeToString(TimeCurrent())+".sqlite";
StringReplace(filename, ":", "."); // символ ":" запрещен в названиях файлов
//--- открываем/создаем базу данных в общей папке терминалов
int db=DatabaseOpen(filename, DATABASE_OPEN_READWRITE | DATABASE_OPEN_CREATE | DATABASE_OPEN_COMMON);
if(db==INVALID_HANDLE)
{
Print("DB: ", filename, " open failed with code ", GetLastError());
return;
}
else
Print("DB: ", filename, " opened successful");
//--- создаем таблицу PASSES
if(!DatabaseExecute(db, "CREATE TABLE PASSES("
"PASS INT PRIMARY KEY NOT NULL,"
"TRADES INT,"
"WIN_TRADES INT,"
"PROFIT REAL,"
"GROSS_PROFIT REAL,"
"GROSS_LOSS REAL,"
"SHARPE_RATIO REAL,"
"PROFIT_FACTOR REAL,"
"RECOVERY_FACTOR REAL,"
"EXPECTED_PAYOFF REAL,"
"ON_TESTER REAL,"
"BL_BALANCE REAL,"
"BL_PROFITFACTOR REAL,"
"BL_EXPECTEDPAYOFF REAL,"
"BL_DD REAL,"
"BL_RECOVERYFACTOR REAL,"
"BL_SHARPE REAL );"))
{
Print("DB: ", filename, " create table failed with code ", GetLastError());
DatabaseClose(db);
return;
}
//--- переменные для чтения фреймов
string name;
ulong pass;
long id;
double value;
double stats[];
//--- переведем указатель фреймов в начало
FrameFirst();
FrameFilter("", STATS_FRAME); // выбираем для работы фреймы с торговой статистикой
//--- переменные для получения статистики из фрейма
int trades;
double win_trades_percent;
double profit, gross_profit, gross_loss;
double sharpe_ratio, profit_factor, recovery_factor, expected_payoff;
double ontester_value; // пользовательский критерий оптимизации
double balance; // Balance
double balance_plus_profitfactor; // Balance+ProfitFactor
double balance_plus_expectedpayoff; // Balance+ExpectedPayoff
double balance_plus_dd; // Balance+EquityDrawdown
double balance_plus_recoveryfactor; // Balance+RecoveryFactor
double balance_plus_sharpe; // Balance+Sharpe
//--- блокируем базу данных на время массовых транзакций
DatabaseTransactionBegin(db);
//--- проходим по фреймам и читаем данные из них
bool failed=false;
while(FrameNext(pass, name, id, value, stats))
{
//Print("Got pass #", pass); // Раскомментировать только для отладки
trades=(int)stats[0];
win_trades_percent=stats[1];
profit=stats[2];
gross_profit=stats[3];
gross_loss=stats[4];
sharpe_ratio=stats[5];
profit_factor=stats[6];
recovery_factor=stats[7];
expected_payoff=stats[8];
ontester_value=stats[9];
balance=stats[10];
balance_plus_profitfactor=stats[11];
balance_plus_expectedpayoff=stats[12];
balance_plus_dd=stats[13];
balance_plus_recoveryfactor=stats[14];
balance_plus_sharpe=stats[15];
/* Раскомментировать только для отладки
PrintFormat("VALUES (%d,%d,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%G,%.2f,%.2f,%2.f,%.2f,%.2f,%.2f,%.2f)",
pass, trades, win_trades_percent, profit, gross_profit, gross_loss, sharpe_ratio,
profit_factor, recovery_factor, expected_payoff, ontester_value, balance,
balance_plus_profitfactor, balance_plus_expectedpayoff, balance_plus_dd, balance_plus_recoveryfactor,
balance_plus_sharpe);
*/
//--- запишем данные в таблицу
string request=StringFormat("INSERT INTO PASSES (PASS,TRADES,WIN_TRADES, PROFIT,GROSS_PROFIT,GROSS_LOSS,"
"SHARPE_RATIO,PROFIT_FACTOR,RECOVERY_FACTOR,EXPECTED_PAYOFF,ON_TESTER,"
"BL_BALANCE,BL_PROFITFACTOR,BL_EXPECTEDPAYOFF,BL_DD,BL_RECOVERYFACTOR,BL_SHARPE) "
"VALUES (%d, %d, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f, %G, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f)",
pass, trades, win_trades_percent, profit, gross_profit, gross_loss, sharpe_ratio,
profit_factor, recovery_factor, expected_payoff, ontester_value, balance,
balance_plus_profitfactor, balance_plus_expectedpayoff, balance_plus_dd, balance_plus_recoveryfactor,
balance_plus_sharpe);
//--- выполним запрос на добавление прохода в таблицу PASSES
if(!DatabaseExecute(db, request))
{
PrintFormat("Failed to insert pass %d with code %d", pass, GetLastError());
failed=true;
break;
}
}
//--- если при выполнении транзакции произошла ошибка, сообщим и завершим работу
if(failed)
{
Print("Transaction failed, error code=", GetLastError());
DatabaseTransactionRollback(db);
DatabaseClose(db);
return;
}
else
{
DatabaseTransactionCommit(db);
Print("Transaction done successful");
}
//--- закроем базу данных
if(db!=INVALID_HANDLE)
{
PrintFormat("Close database with handle=%d", db);
PrintFormat("Database stored in file '%s'", filename);
DatabaseClose(db);
}
//---
}
|