MT4 Files

Check-in [c006007ae5]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Consolidated
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:c006007ae56a20d6e026374cd133f4d11a066b9f
User & Date: onagano 2011-04-20 08:53:38
Context
2011-04-20
12:05
Improved the logic of copyRates check-in: 8b84736cc6 user: onagano tags: trunk
08:53
Consolidated check-in: c006007ae5 user: onagano tags: trunk
2011-04-19
09:06
Merged with exec_order branch check-in: 1db6efd34a user: onagano tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to experts/MOB_executeOrder.mq4.

34
35
36
37
38
39
40
41


42
43
44
45
46
47
48
..
50
51
52
53
54
55
56

57
58
59
60
61
62
63
64
65
66
67
68
...
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
...
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
...
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
...
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
...
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
...
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
...
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
...
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
...
445
446
447
448
449
450
451























452
453
454
455
456
457
458
459
460
461
462
463
464
...
480
481
482
483
484
485
486



487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530








531
532
533
534
535
536
537
...
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
...
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926




















927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
...
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016




























1017

















































1018
1019
1020


1021





1022
1023
1024
int      mob_fetchedAll(int stmtId);
int      mob_insertTick(int stmtId, datetime dt, int fraction, double vals[]);
int      mob_insertBar(int stmtId, datetime dt, double vals[]);
int      mob_copyRates(int stmtId, double rates[][6], int size, int start, int end);
double   mob_selectDouble(string sql, double defaultVal);
int      mob_selectInt(string sql, int defaultVal);
datetime mob_selectDatetime(string sql, datetime defaultVal);
int      checkMOBError(int rc);


datetime mob_time();
int      mob_strcpy(string dest, int size, string src);
#import "stdlib.ex4"
string   ErrorDescription(int error_code);
#import

#define OPE_SEND           1
................................................................................
#define OPE_CLOSEBY        3
#define OPE_DELETE         4
#define OPE_MODIFY         5
#define OPE_DUMP_TRADES    6
#define OPE_DUMP_HISTORY   7
#define OPE_GET_ACCOUNT    8
#define OPE_GET_STATUS     9


#define ORD_DEFAULT_SLIPPAGE 3

//--- input parameters
extern string    ExtDataSourceName = "testpostgresql";
extern string    ExtUsername       = "";
extern string    ExtPassword       = "";
extern string    ExtTablePrefix    = "MOB_";

//--- global variables
string orderTable       = "ORDER";
int    selectOrderStmt  = 0;
................................................................................
      Alert("ERROR: [Allow DLL imports] NOT Checked.");
      return (-1);
   }
//----
   mob_create();
   int rc;
   
   rc = checkMOBError(mob_open(ExtDataSourceName, ExtUsername, ExtPassword));
   if (rc < 0) return (rc);

   rc = checkMOBError(mob_setAutoCommit(true));
   if (rc < 0) return (rc);
   
   // Preparing order table
   
   orderTable = ExtTablePrefix + orderTable;
   rc = checkMOBError(createTableIfNotExists(orderTable, createOrderTableSQL(orderTable)));
   if (rc < 0) return (rc);

   // Regstering select order statement
   
   rc = checkMOBError(mob_registerStatement(selectOrderSQL(orderTable)));
   if (rc < 0) return (rc);
   selectOrderStmt = rc;

   int i = 1;
   mob_bindIntColumn       (selectOrderStmt, i, ordId);              i++;
   mob_bindIntColumn       (selectOrderStmt, i, ordOperation);       i++;
   mob_bindIntColumn       (selectOrderStmt, i, ordTicket);          i++;
................................................................................
   mob_bindDatetimeColumn  (selectOrderStmt, i, ordExpiration);      i++;
   mob_bindIntColumn       (selectOrderStmt, i, ordArrowColor);      i++;
   mob_bindIntColumn       (selectOrderStmt, i, ordErrorNumber);     i++;
   mob_bindStringColumn    (selectOrderStmt, i, ordErrorMessage);    i++;

   // Registering update order statement
   
   rc = checkMOBError(mob_registerStatement(updateOrderSQL(orderTable)));
   if (rc < 0) return (rc);
   updateOrderStmt = rc;

   i = 1;
   mob_bindIntParameter       (updateOrderStmt, i, ordOperation);       i++;
   mob_bindIntParameter       (updateOrderStmt, i, ordTicket);          i++;
   mob_bindIntParameter       (updateOrderStmt, i, ordOppositeTicket);  i++;
................................................................................
   ordSymbolSize = StringLen(ordSymbol);
   ordCommentSize = StringLen(ordComment);
   ordErrorMessageSize = StringLen(ordErrorMessage);

   // Preparing trade table
   
   tradeTable = ExtTablePrefix + tradeTable;
   rc = checkMOBError(createTableIfNotExists(tradeTable, createTradeTableSQL(tradeTable)));
   if (rc < 0) return (rc);

   // Registering truncate trade statement
   
   rc = checkMOBError(mob_registerStatement(truncateTradeSQL(tradeTable)));
   if (rc < 0) return (rc);
   truncateTradeStmt = rc;

   // Registering insert trade statement
   
   rc = checkMOBError(mob_registerStatement(insertTradeSQL(tradeTable)));
   if (rc < 0) return (rc);
   insertTradeStmt = rc;

   i = 1;
   mob_bindIntParameter       (insertTradeStmt, i, trdTicket);       i++;
   mob_bindDatetimeParameter  (insertTradeStmt, i, trdOpenTime);     i++;
   mob_bindIntParameter       (insertTradeStmt, i, trdType);         i++;
................................................................................
   mob_bindDatetimeParameter  (insertTradeStmt, i, trdExpiration);   i++;
   mob_bindIntParameter       (insertTradeStmt, i, trdMagicNumber);  i++;
   mob_bindStringParameter    (insertTradeStmt, i, trdComment);      i++;

   // Preparing history table
   
   historyTable = ExtTablePrefix + historyTable;
   rc = checkMOBError(createTableIfNotExists(historyTable, createTradeTableSQL(historyTable)));
   if (rc < 0) return (rc);

   // Registering truncate history statement
   
   rc = checkMOBError(mob_registerStatement(truncateTradeSQL(historyTable)));
   if (rc < 0) return (rc);
   truncateHistoryStmt = rc;

   // Registering insert history statement
   
   rc = checkMOBError(mob_registerStatement(insertTradeSQL(historyTable)));
   if (rc < 0) return (rc);
   insertHistoryStmt = rc;

   i = 1;
   mob_bindIntParameter       (insertHistoryStmt, i, trdTicket);       i++;
   mob_bindDatetimeParameter  (insertHistoryStmt, i, trdOpenTime);     i++;
   mob_bindIntParameter       (insertHistoryStmt, i, trdType);         i++;
................................................................................
   mob_bindDatetimeParameter  (insertHistoryStmt, i, trdExpiration);   i++;
   mob_bindIntParameter       (insertHistoryStmt, i, trdMagicNumber);  i++;
   mob_bindStringParameter    (insertHistoryStmt, i, trdComment);      i++;

   // Preparing status table

   statusTable = ExtTablePrefix + statusTable;
   rc = checkMOBError(createTableIfNotExists(statusTable, createTradeTableSQL(statusTable)));
   if (rc < 0) return (rc);

   // Registering delete status statement
   
   rc = checkMOBError(mob_registerStatement(deleteTradeSQL(statusTable)));
   if (rc < 0) return (rc);
   deleteStatusStmt = rc;

   i = 1;
   mob_bindIntParameter       (deleteStatusStmt, i, ordTicket);       i++;

   // Registering insert status statement
   
   rc = checkMOBError(mob_registerStatement(insertTradeSQL(statusTable)));
   if (rc < 0) return (rc);
   insertStatusStmt = rc;

   i = 1;
   mob_bindIntParameter       (insertStatusStmt, i, trdTicket);       i++;
   mob_bindDatetimeParameter  (insertStatusStmt, i, trdOpenTime);     i++;
   mob_bindIntParameter       (insertStatusStmt, i, trdType);         i++;
................................................................................

   trdSymbolSize = StringLen(trdSymbol);
   trdCommentSize = StringLen(trdComment);

   // Preparing account table
   
   accountTable = ExtTablePrefix + accountTable;
   rc = checkMOBError(createTableIfNotExists(accountTable, createAccountTableSQL(accountTable)));
   if (rc < 0) return (rc);

   // Registering insert account statement
   
   rc = checkMOBError(mob_registerStatement(insertAccountSQL(accountTable)));
   if (rc < 0) return (rc);
   insertAccountStmt = rc;

   i = 1;
   mob_bindDatetimeParameter  (insertAccountStmt, i, accServerTime);    i++;
   mob_bindDoubleParameter    (insertAccountStmt, i, accBalance);       i++;
   mob_bindDoubleParameter    (insertAccountStmt, i, accEquity);        i++;
................................................................................
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   int rc = checkMOBError(mob_close());
   if (rc < 0) return (rc);
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
................................................................................
   int rc = selectOrders();
   if (rc < 0) return (rc);
//----
   return(0);
  }
//+------------------------------------------------------------------+

int createTableIfNotExists(string tableName, string sql, bool drop = false) {
   int rc = 0;

   // MySQL has 'CREATE TABLE IF NOT EXISTS ...'
   // while PostgreSQL has 'DROP TABLE IF EXISTS ...'
 
   if (drop) rc = mob_execute("drop table " + tableName);

   rc = mob_selectInt("select count(*) from " + tableName, -1);
   bool exist = 0 <= rc;
   
   if (!exist) {
      rc = mob_execute(sql);
   }
   
   return (rc);
}

string createOrderTableSQL(string tableName) {
   // MySQL has AUTO_INCREMENT option at column definition,
   // but PostgreSQL needs SEQUENCE object...
   string seqName = tableName + "_ID_SEQ";
   string opeIndName = tableName + "_OPEIND";
   string sql = ""
      + "drop sequence if exists " + seqName + ";"
      + "create sequence " + seqName + ";"
      + "create table " + tableName + " ("
      + "  id integer default nextval('" + seqName + "') primary key"
      + ", operation integer default 0"
      + ", ticket integer default -1"
      + ", opposite_ticket integer default -1"
      + ", symbol varchar(10) default ''"
      + ", type integer default -1"
      + ", lots double precision default 0.0"
      + ", open_price double precision default 0.0"
      + ", close_price double precision default 0.0"
      + ", slippage integer default " + ORD_DEFAULT_SLIPPAGE
      + ", stop_loss double precision default 0.0"
      + ", take_profit double precision default 0.0"
      + ", comment varchar(140) default ''"
      + ", magic_number integer default 0"
      + ", expiration timestamp with time zone default '1970-01-01 00:00:00-00'"
      + ", arrow_color integer default " + CLR_NONE
      + ", error_number integer default 0"
      + ", error_message varchar(140) default ''"
      + ");"
      + "drop index if exists " + opeIndName + ";"
      + "create index " + opeIndName + " on " + tableName + " (operation)";
   return (sql);
................................................................................
      + ", arrow_color"
      + ", error_number"
      + ", error_message"
      + " from " + tableName + " where "
      + "operation > 0 order by id";
   return (sql);
}
























int selectOrders() {
   int rc = 0;

   rc = checkMOBError(mob_selectToFetch(selectOrderStmt));
   while (checkMOBError(mob_fetch(selectOrderStmt)) != 0) {
   
      switch (ordOperation[0]) {
      case OPE_SEND:
         orderSend();
         break;
      case OPE_CLOSE:
         orderClose();
................................................................................
         break;
      case OPE_GET_ACCOUNT:
         insertAccount();
         break;
      case OPE_GET_STATUS:
         getStatusInTransaction();
         break;



      default:
         string mesg = "Unknown operation: " + ordOperation[0];
         Print(mesg);
         ordErrorNumber[0] = -1;
         mob_strcpy(ordErrorMessage, ordErrorMessageSize, mesg);
      }
      
      ordOperation[0] = - ordOperation[0];
      rc = checkMOBError(mob_executeStatement(updateOrderStmt));
   }
   checkMOBError(mob_fetchedAll(selectOrderStmt));
   
   return (rc);
}

string updateOrderSQL(string tableName) {
   string sql = "update " + tableName + " set"
      + "  operation = ?"
      + ", ticket = ?"
      + ", opposite_ticket = ?"
      + ", symbol = ?"
      + ", type = ?"
      + ", lots = ?"
      + ", open_price = ?"
      + ", close_price = ?"
      + ", slippage = ?"
      + ", stop_loss = ?"
      + ", take_profit = ?"
      + ", comment = ?"
      + ", magic_number = ?"
      + ", expiration = ?"
      + ", arrow_color = ?"
      + ", error_number = ?"
      + ", error_message = ?"
      + " where id = ?";
   return (sql);
}

void getServerResponse() {
   int err = GetLastError();
   string errMesg = ErrorDescription(err);
   ordErrorNumber[0] = err;
   mob_strcpy(ordErrorMessage, ordErrorMessageSize, errMesg);
   Print("#", err, ":", ordErrorMessage, "(", StringLen(ordErrorMessage), ")");








}

void orderSend() {
   double margin;
   double thePip    = getPipSize(ordSymbol);
   int    theDigits = MarketInfo(ordSymbol, MODE_DIGITS);
   
................................................................................
      getServerResponse();
   }
}

string createTradeTableSQL(string tableName) {
   string sql = "create table " + tableName + " ("
      + "  ticket integer primary key"
      + ", open_time timestamp with time zone default '1970-01-01 00:00:00-00'"
      + ", type integer default -1"
      + ", lots double precision default 0.0"
      + ", symbol varchar(10) default ''"
      + ", open_price double precision default 0.0"
      + ", stop_loss double precision default 0.0"
      + ", take_profit double precision default 0.0"
      + ", close_time timestamp with time zone default '1970-01-01 00:00:00-00'"
      + ", close_price double precision default 0.0"
      + ", commission double precision default 0.0"
      + ", swap double precision default 0.0"
      + ", profit double precision default 0.0"
      + ", expiration timestamp with time zone default '1970-01-01 00:00:00-00'"
      + ", magic_number integer default 0"
      + ", comment varchar(140) default ''"
      + ")";
   return (sql);
}

string truncateTradeSQL(string tableName) {
................................................................................
   } else {
      truncateStmt = truncateTradeStmt;
      insertStmt = insertTradeStmt;
      n = OrdersTotal();
      pool = MODE_TRADES;
   }

   rc = checkMOBError(mob_executeStatement(truncateStmt));
   if (rc < 0) {
      getDatabaseResponse();
      return (rc);
   }
   for (int i = 0; i < n; i++) {
      if (OrderSelect(i, SELECT_BY_POS, pool)) {
         bindTradeParameters();
         rc = checkMOBError(mob_executeStatement(insertStmt));
         if (rc < 0) {
            getDatabaseResponse();
            return (rc);
         }
      } else {
         getServerResponse();
      }
   }
   
   return (rc);
}

void getDatabaseResponse() {
   int err = mob_getLastErrorNo();
   string errMesg = mob_getLastErrorMesg();
   ordErrorNumber[0] = err;
   mob_strcpy(ordErrorMessage, ordErrorMessageSize, errMesg);
   //Print("#", err, ":", ordErrorMessage, "(", StringLen(ordErrorMessage), ")");
}

void dumpTradesInTransaction(bool history) {
   mob_setAutoCommit(false);
   int rc = dumpTrades(history);
   if (rc < 0) {
      mob_rollback();
   } else {
      mob_commit();
   }
   mob_setAutoCommit(true);
}





















void getStatusInTransaction() {
   mob_setAutoCommit(false);
   int rc = getStatus();
   if (rc < 0) {
      mob_rollback();
   } else {
      mob_commit();
   }
   mob_setAutoCommit(true);
}

int getStatus() {
   int rc = 0;
   rc = checkMOBError(mob_executeStatement(deleteStatusStmt));
   if (rc < 0) {
      getDatabaseResponse();
      return (rc);
   }
   if (OrderSelect(ordTicket[0], SELECT_BY_TICKET)) {
      bindTradeParameters();
      rc = checkMOBError(mob_executeStatement(insertStatusStmt));
      if (rc < 0) {
         getDatabaseResponse();
         return (rc);
      }
   } else {
      getServerResponse();
   }
   return (rc);
}

string createAccountTableSQL(string tableName) {
   string seqName = tableName + "_ID_SEQ";
   string sql = ""
      + "drop sequence if exists " + seqName + ";"
      + "create sequence " + seqName + ";"
      + "create table " + tableName + " ("
      + "  id integer default nextval('" + seqName + "') primary key"
      + ", server_time timestamp with time zone default '1970-01-01 00:00:00-00'"
      + ", balance double precision"
      + ", equity double precision"
      + ", margin double precision"
      + ", free_margin double precision"
      + ", profit double precision"
      + ", open_trades integer"
      + ", closed_trades integer"
................................................................................
   accEquity[0]         = AccountEquity();
   accMargin[0]         = AccountMargin();
   accFreeMargin[0]     = AccountFreeMargin();
   accProfit[0]         = AccountProfit();
   accOpenTrades[0]     = OrdersTotal();
   accClosedTrades[0]   = OrdersHistoryTotal();

   int rc = checkMOBError(mob_executeStatement(insertAccountStmt));
   if (rc < 0) {
      getDatabaseResponse();
   }
}

double getPipSize(string symbol) {
   double pip    = 0.0;
   double point  = MarketInfo(symbol, MODE_POINT);
   int    digits = MarketInfo(symbol, MODE_DIGITS);
   switch (digits) {
      case 5:
      case 3:
         pip = NormalizeDouble(point * 10, digits);
         break;




























      case 4:

















































      case 2:
         pip = NormalizeDouble(point, digits);
         break;


   }





   return (pip);
}








|
>
>







 







>




|







 







|


|





|




|







 







|







 







|




|





|







 







|




|





|







 







|




|








|







 







|




|







 







|







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<



<


<
<

|













|







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>




|
|







 







>
>
>








|

|




<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<





|
>
>
>
>
>
>
>
>







 







|






|




|







 







|







|












<
<
<
<
<
<
<
<










>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>












<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<

<

<
<

|
|







 







|





|
|
|
|
|
|
|
|
<
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
<
<
>
>

>
>
>
>
>
|


34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
..
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
...
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
...
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
...
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
...
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
...
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
...
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
...
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
...
373
374
375
376
377
378
379


















380
381
382

383
384


385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
...
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
...
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509























510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
...
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
...
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901








902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943




















944

945


946
947
948
949
950
951
952
953
954
955
...
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997

998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076


1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
int      mob_fetchedAll(int stmtId);
int      mob_insertTick(int stmtId, datetime dt, int fraction, double vals[]);
int      mob_insertBar(int stmtId, datetime dt, double vals[]);
int      mob_copyRates(int stmtId, double rates[][6], int size, int start, int end);
double   mob_selectDouble(string sql, double defaultVal);
int      mob_selectInt(string sql, int defaultVal);
datetime mob_selectDatetime(string sql, datetime defaultVal);
int      createTableIfNotExists(string tableName, string sql);
string   getPeriodSymbol(int period_XX);
double   getPipSize(string symbol);
datetime mob_time();
int      mob_strcpy(string dest, int size, string src);
#import "stdlib.ex4"
string   ErrorDescription(int error_code);
#import

#define OPE_SEND           1
................................................................................
#define OPE_CLOSEBY        3
#define OPE_DELETE         4
#define OPE_MODIFY         5
#define OPE_DUMP_TRADES    6
#define OPE_DUMP_HISTORY   7
#define OPE_GET_ACCOUNT    8
#define OPE_GET_STATUS     9
#define OPE_COPY_RATES     10

#define ORD_DEFAULT_SLIPPAGE 3

//--- input parameters
extern string    ExtDataSourceName = "testh2db";
extern string    ExtUsername       = "";
extern string    ExtPassword       = "";
extern string    ExtTablePrefix    = "MOB_";

//--- global variables
string orderTable       = "ORDER";
int    selectOrderStmt  = 0;
................................................................................
      Alert("ERROR: [Allow DLL imports] NOT Checked.");
      return (-1);
   }
//----
   mob_create();
   int rc;
   
   rc = mob_open(ExtDataSourceName, ExtUsername, ExtPassword);
   if (rc < 0) return (rc);

   rc = mob_setAutoCommit(true);
   if (rc < 0) return (rc);
   
   // Preparing order table
   
   orderTable = ExtTablePrefix + orderTable;
   rc = createTableIfNotExists(orderTable, createOrderTableSQL(orderTable));
   if (rc < 0) return (rc);

   // Regstering select order statement
   
   rc = mob_registerStatement(selectOrderSQL(orderTable));
   if (rc < 0) return (rc);
   selectOrderStmt = rc;

   int i = 1;
   mob_bindIntColumn       (selectOrderStmt, i, ordId);              i++;
   mob_bindIntColumn       (selectOrderStmt, i, ordOperation);       i++;
   mob_bindIntColumn       (selectOrderStmt, i, ordTicket);          i++;
................................................................................
   mob_bindDatetimeColumn  (selectOrderStmt, i, ordExpiration);      i++;
   mob_bindIntColumn       (selectOrderStmt, i, ordArrowColor);      i++;
   mob_bindIntColumn       (selectOrderStmt, i, ordErrorNumber);     i++;
   mob_bindStringColumn    (selectOrderStmt, i, ordErrorMessage);    i++;

   // Registering update order statement
   
   rc = mob_registerStatement(updateOrderSQL(orderTable));
   if (rc < 0) return (rc);
   updateOrderStmt = rc;

   i = 1;
   mob_bindIntParameter       (updateOrderStmt, i, ordOperation);       i++;
   mob_bindIntParameter       (updateOrderStmt, i, ordTicket);          i++;
   mob_bindIntParameter       (updateOrderStmt, i, ordOppositeTicket);  i++;
................................................................................
   ordSymbolSize = StringLen(ordSymbol);
   ordCommentSize = StringLen(ordComment);
   ordErrorMessageSize = StringLen(ordErrorMessage);

   // Preparing trade table
   
   tradeTable = ExtTablePrefix + tradeTable;
   rc = createTableIfNotExists(tradeTable, createTradeTableSQL(tradeTable));
   if (rc < 0) return (rc);

   // Registering truncate trade statement
   
   rc = mob_registerStatement(truncateTradeSQL(tradeTable));
   if (rc < 0) return (rc);
   truncateTradeStmt = rc;

   // Registering insert trade statement
   
   rc = mob_registerStatement(insertTradeSQL(tradeTable));
   if (rc < 0) return (rc);
   insertTradeStmt = rc;

   i = 1;
   mob_bindIntParameter       (insertTradeStmt, i, trdTicket);       i++;
   mob_bindDatetimeParameter  (insertTradeStmt, i, trdOpenTime);     i++;
   mob_bindIntParameter       (insertTradeStmt, i, trdType);         i++;
................................................................................
   mob_bindDatetimeParameter  (insertTradeStmt, i, trdExpiration);   i++;
   mob_bindIntParameter       (insertTradeStmt, i, trdMagicNumber);  i++;
   mob_bindStringParameter    (insertTradeStmt, i, trdComment);      i++;

   // Preparing history table
   
   historyTable = ExtTablePrefix + historyTable;
   rc = createTableIfNotExists(historyTable, createTradeTableSQL(historyTable));
   if (rc < 0) return (rc);

   // Registering truncate history statement
   
   rc = mob_registerStatement(truncateTradeSQL(historyTable));
   if (rc < 0) return (rc);
   truncateHistoryStmt = rc;

   // Registering insert history statement
   
   rc = mob_registerStatement(insertTradeSQL(historyTable));
   if (rc < 0) return (rc);
   insertHistoryStmt = rc;

   i = 1;
   mob_bindIntParameter       (insertHistoryStmt, i, trdTicket);       i++;
   mob_bindDatetimeParameter  (insertHistoryStmt, i, trdOpenTime);     i++;
   mob_bindIntParameter       (insertHistoryStmt, i, trdType);         i++;
................................................................................
   mob_bindDatetimeParameter  (insertHistoryStmt, i, trdExpiration);   i++;
   mob_bindIntParameter       (insertHistoryStmt, i, trdMagicNumber);  i++;
   mob_bindStringParameter    (insertHistoryStmt, i, trdComment);      i++;

   // Preparing status table

   statusTable = ExtTablePrefix + statusTable;
   rc = createTableIfNotExists(statusTable, createTradeTableSQL(statusTable));
   if (rc < 0) return (rc);

   // Registering delete status statement
   
   rc = mob_registerStatement(deleteTradeSQL(statusTable));
   if (rc < 0) return (rc);
   deleteStatusStmt = rc;

   i = 1;
   mob_bindIntParameter       (deleteStatusStmt, i, ordTicket);       i++;

   // Registering insert status statement
   
   rc = mob_registerStatement(insertTradeSQL(statusTable));
   if (rc < 0) return (rc);
   insertStatusStmt = rc;

   i = 1;
   mob_bindIntParameter       (insertStatusStmt, i, trdTicket);       i++;
   mob_bindDatetimeParameter  (insertStatusStmt, i, trdOpenTime);     i++;
   mob_bindIntParameter       (insertStatusStmt, i, trdType);         i++;
................................................................................

   trdSymbolSize = StringLen(trdSymbol);
   trdCommentSize = StringLen(trdComment);

   // Preparing account table
   
   accountTable = ExtTablePrefix + accountTable;
   rc = createTableIfNotExists(accountTable, createAccountTableSQL(accountTable));
   if (rc < 0) return (rc);

   // Registering insert account statement
   
   rc = mob_registerStatement(insertAccountSQL(accountTable));
   if (rc < 0) return (rc);
   insertAccountStmt = rc;

   i = 1;
   mob_bindDatetimeParameter  (insertAccountStmt, i, accServerTime);    i++;
   mob_bindDoubleParameter    (insertAccountStmt, i, accBalance);       i++;
   mob_bindDoubleParameter    (insertAccountStmt, i, accEquity);        i++;
................................................................................
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   int rc = mob_close();
   if (rc < 0) return (rc);
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
................................................................................
   int rc = selectOrders();
   if (rc < 0) return (rc);
//----
   return(0);
  }
//+------------------------------------------------------------------+



















string createOrderTableSQL(string tableName) {
   // MySQL has AUTO_INCREMENT option at column definition,
   // but PostgreSQL needs SEQUENCE object...

   string opeIndName = tableName + "_OPEIND";
   string sql = ""


      + "create table " + tableName + " ("
      + "  id integer identity"
      + ", operation integer default 0"
      + ", ticket integer default -1"
      + ", opposite_ticket integer default -1"
      + ", symbol varchar(10) default ''"
      + ", type integer default -1"
      + ", lots double precision default 0.0"
      + ", open_price double precision default 0.0"
      + ", close_price double precision default 0.0"
      + ", slippage integer default " + ORD_DEFAULT_SLIPPAGE
      + ", stop_loss double precision default 0.0"
      + ", take_profit double precision default 0.0"
      + ", comment varchar(140) default ''"
      + ", magic_number integer default 0"
      + ", expiration timestamp default '1970-01-01 00:00:00'"
      + ", arrow_color integer default " + CLR_NONE
      + ", error_number integer default 0"
      + ", error_message varchar(140) default ''"
      + ");"
      + "drop index if exists " + opeIndName + ";"
      + "create index " + opeIndName + " on " + tableName + " (operation)";
   return (sql);
................................................................................
      + ", arrow_color"
      + ", error_number"
      + ", error_message"
      + " from " + tableName + " where "
      + "operation > 0 order by id";
   return (sql);
}

string updateOrderSQL(string tableName) {
   string sql = "update " + tableName + " set"
      + "  operation = ?"
      + ", ticket = ?"
      + ", opposite_ticket = ?"
      + ", symbol = ?"
      + ", type = ?"
      + ", lots = ?"
      + ", open_price = ?"
      + ", close_price = ?"
      + ", slippage = ?"
      + ", stop_loss = ?"
      + ", take_profit = ?"
      + ", comment = ?"
      + ", magic_number = ?"
      + ", expiration = ?"
      + ", arrow_color = ?"
      + ", error_number = ?"
      + ", error_message = ?"
      + " where id = ?";
   return (sql);
}

int selectOrders() {
   int rc = 0;

   rc = mob_selectToFetch(selectOrderStmt);
   while (mob_fetch(selectOrderStmt) != 0) {
   
      switch (ordOperation[0]) {
      case OPE_SEND:
         orderSend();
         break;
      case OPE_CLOSE:
         orderClose();
................................................................................
         break;
      case OPE_GET_ACCOUNT:
         insertAccount();
         break;
      case OPE_GET_STATUS:
         getStatusInTransaction();
         break;
      case OPE_COPY_RATES:
         copyRates();
         break;
      default:
         string mesg = "Unknown operation: " + ordOperation[0];
         Print(mesg);
         ordErrorNumber[0] = -1;
         mob_strcpy(ordErrorMessage, ordErrorMessageSize, mesg);
      }
      
      ordOperation[0] = - ordOperation[0];
      rc = mob_executeStatement(updateOrderStmt);
   }
   mob_fetchedAll(selectOrderStmt);
   
   return (rc);
}
























void getServerResponse() {
   int err = GetLastError();
   string errMesg = ErrorDescription(err);
   ordErrorNumber[0] = err;
   mob_strcpy(ordErrorMessage, ordErrorMessageSize, errMesg);
   Print("Server error #", err, ": ", ordErrorMessage, "(", StringLen(ordErrorMessage), ")");
}

void getDatabaseResponse() {
   int err = mob_getLastErrorNo();
   string errMesg = mob_getLastErrorMesg();
   ordErrorNumber[0] = err;
   mob_strcpy(ordErrorMessage, ordErrorMessageSize, errMesg);
   //Print("Database error #", err, ": ", ordErrorMessage, "(", StringLen(ordErrorMessage), ")");
}

void orderSend() {
   double margin;
   double thePip    = getPipSize(ordSymbol);
   int    theDigits = MarketInfo(ordSymbol, MODE_DIGITS);
   
................................................................................
      getServerResponse();
   }
}

string createTradeTableSQL(string tableName) {
   string sql = "create table " + tableName + " ("
      + "  ticket integer primary key"
      + ", open_time timestamp default '1970-01-01 00:00:00'"
      + ", type integer default -1"
      + ", lots double precision default 0.0"
      + ", symbol varchar(10) default ''"
      + ", open_price double precision default 0.0"
      + ", stop_loss double precision default 0.0"
      + ", take_profit double precision default 0.0"
      + ", close_time timestamp default '1970-01-01 00:00:00'"
      + ", close_price double precision default 0.0"
      + ", commission double precision default 0.0"
      + ", swap double precision default 0.0"
      + ", profit double precision default 0.0"
      + ", expiration timestamp default '1970-01-01 00:00:00'"
      + ", magic_number integer default 0"
      + ", comment varchar(140) default ''"
      + ")";
   return (sql);
}

string truncateTradeSQL(string tableName) {
................................................................................
   } else {
      truncateStmt = truncateTradeStmt;
      insertStmt = insertTradeStmt;
      n = OrdersTotal();
      pool = MODE_TRADES;
   }

   rc = mob_executeStatement(truncateStmt);
   if (rc < 0) {
      getDatabaseResponse();
      return (rc);
   }
   for (int i = 0; i < n; i++) {
      if (OrderSelect(i, SELECT_BY_POS, pool)) {
         bindTradeParameters();
         rc = mob_executeStatement(insertStmt);
         if (rc < 0) {
            getDatabaseResponse();
            return (rc);
         }
      } else {
         getServerResponse();
      }
   }
   
   return (rc);
}









void dumpTradesInTransaction(bool history) {
   mob_setAutoCommit(false);
   int rc = dumpTrades(history);
   if (rc < 0) {
      mob_rollback();
   } else {
      mob_commit();
   }
   mob_setAutoCommit(true);
}

int getStatus() {
   int rc = 0;
   rc = mob_executeStatement(deleteStatusStmt);
   if (rc < 0) {
      getDatabaseResponse();
      return (rc);
   }
   if (OrderSelect(ordTicket[0], SELECT_BY_TICKET)) {
      bindTradeParameters();
      rc = mob_executeStatement(insertStatusStmt);
      if (rc < 0) {
         getDatabaseResponse();
         return (rc);
      }
   } else {
      getServerResponse();
   }
   return (rc);
}

void getStatusInTransaction() {
   mob_setAutoCommit(false);
   int rc = getStatus();
   if (rc < 0) {
      mob_rollback();
   } else {
      mob_commit();
   }
   mob_setAutoCommit(true);
}





















string createAccountTableSQL(string tableName) {

   string sql = ""


      + "create table " + tableName + " ("
      + "  id integer identity"
      + ", server_time timestamp default '1970-01-01 00:00:00'"
      + ", balance double precision"
      + ", equity double precision"
      + ", margin double precision"
      + ", free_margin double precision"
      + ", profit double precision"
      + ", open_trades integer"
      + ", closed_trades integer"
................................................................................
   accEquity[0]         = AccountEquity();
   accMargin[0]         = AccountMargin();
   accFreeMargin[0]     = AccountFreeMargin();
   accProfit[0]         = AccountProfit();
   accOpenTrades[0]     = OrdersTotal();
   accClosedTrades[0]   = OrdersHistoryTotal();

   int rc = mob_executeStatement(insertAccountStmt);
   if (rc < 0) {
      getDatabaseResponse();
   }
}

string createBarTableSQL(string tableName) {
   string sql = "create table " + tableName + " ("
      + "  time timestamp primary key"
      + ", open double precision"
      + ", high double precision"
      + ", low double precision"
      + ", close double precision"
      + ", volume double precision"

      + ")";
   return (sql);
}

string insertBarSQL(string tableName) {
   string sql = "insert into " + tableName
      + " (time, open, high, low, close, volume) values (?, ?, ?, ?, ?, ?)";
   return (sql);
}

void copyRates() {
   string symbol = ordSymbol;
   int    period = ordType[0];
   string tableName = ExtTablePrefix + symbol + "_" + getPeriodSymbol(period);
   
   createTableIfNotExists(tableName, createBarTableSQL(tableName));

   int count      = mob_selectInt("select count(*) from " + tableName, -1);
   datetime dtMax = mob_selectDatetime("select max(time) from " + tableName, -1);
   datetime dtMin = mob_selectDatetime("select min(time) from " + tableName, -1);
   int start;
   int end;
   int rv;

   if (count <= 0) {
      start = 0;
      end = iBars(symbol, period) - 1; // Exclude the latest bar.
      rv = copyRatesBetween(tableName, start, end, symbol, period);
   } else {
      datetime dts[];
      int nBars = ArrayCopySeries(dts, MODE_TIME, symbol, period);
      int iMax = ArrayBsearch(dts, dtMax, WHOLE_ARRAY, 0 , MODE_DESCEND);
      int iMin = ArrayBsearch(dts, dtMin, WHOLE_ARRAY, 0 , MODE_DESCEND);
      start = 0;
      end = nBars - (iMin + 1);
      rv += copyRatesBetween(tableName, start, end, symbol, period);
      start = nBars - iMax;
      end = nBars - 1; // Exclude the latest bar.
      rv += copyRatesBetween(tableName, start, end, symbol, period);
   }

   ordMagicNumber[0] = rv;
}

int copyRatesBetween(string tableName, int start, int end, string symbol, int timeframe) {
   if (start == end) return (0);
   if (start > end) {
      Print("Wrong indices. start ", start, " should be smaller than end ", end);
      return (-1);
   }
   if (start < 0) {
      Print("Start ", start, " cannot be smaller than zero");
      return (-1);
   }
   
   double rates[][6];
   int nBars = ArrayCopyRates(rates, symbol, timeframe);
   if (nBars < 0) {
      int ec = GetLastError();
      Print("ArrayCopyRates causess ", ec, ", ", ErrorDescription(ec));
      return (nBars);
   }
   if (nBars < end) {
      Print("End index ", end,  " is larger than available size ", nBars);
      return (-1);
   }

   int rc = 0;
   int rv = 0;
   
   int insertBarStmt = mob_registerStatement(insertBarSQL(tableName));

   rc = mob_setAutoCommit(false);

   // RateInfo structure's order is OLHCV, which will be adjusted to OHLCV in database.
   rc = mob_copyRates(insertBarStmt, rates, ArraySize(rates), start, end);
   if (rc < 0) {
      rc = mob_rollback();
   } else {


      rv = rc;
      rc = mob_commit();
   }

   rc = mob_setAutoCommit(true);

   rc = mob_unregisterStatement(insertBarStmt);

   return(rv);
}

Changes to experts/MOB_insertData.mq4.

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
..
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
..
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
...
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
...
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
...
173
174
175
176
177
178
179
180










































































int      mob_unregisterStatement(int stmtId);
int      mob_insertTick(int stmtId, datetime dt, int fraction, double vals[]);
int      mob_insertBar(int stmtId, datetime dt, double vals[]);
int      mob_copyRates(int stmtId, double rates[][6], int size, int start, int end);
double   mob_selectDouble(string sql, double defaultVal);
int      mob_selectInt(string sql, int defaultVal);
datetime mob_selectDatetime(string sql, datetime defaultVal);
int      checkMOBError(int rc);
string   getDefaultTableName(bool isBar = true);
string   getPeriodSymbol(int period_XX);
int      createTableIfNotExists(string tableName, bool isBar = true);
string   insertSQL(string tableName, bool isBar = true);
datetime mob_time();
#import

//---- input parameters
extern string    ExtDataSourceName = "testpostgresql";
extern string    ExtUsername       = "";
extern string    ExtPassword       = "";
extern string    ExtTablePrefix    = "MOB_";

int      insertTick;
int      insertBar;
datetime lastTickTime;
................................................................................
      return (-1);
   }
//----
   mob_create();
   int rc;
   
   if (ExtUsername == "")
      rc = checkMOBError(mob_open(ExtDataSourceName, NULL, NULL));
   else
      rc = checkMOBError(mob_open(ExtDataSourceName, ExtUsername, ExtPassword));
   if (rc < 0) return (rc);

   rc = checkMOBError(mob_setAutoCommit(true));
   if (rc < 0) return (rc);
   
   // Prepare tick table
   string tickTable = ExtTablePrefix + getDefaultTableName(false);
   rc = prepareTable(tickTable, false);
   if (rc < 0) return (rc);
	
................................................................................
int deinit()
  {
//----
   // Insert the very last bar if the time passed enough.
   datetime serverTime = Time[0]; // Doesn't proceed on weekends.
   datetime currentTime = mob_time(); // Native time() API.
   if ((currentTime - serverTime) >= Period() * 60) {
      checkMOBError(insertBarAt(0));
   }

   int rc = checkMOBError(mob_close());
   if (rc < 0) return (rc);
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
................................................................................
   return(0);
  }
//+------------------------------------------------------------------+

int prepareTable(string tableName, bool isBar) {
   int rc;
   
   rc = checkMOBError(createTableIfNotExists(tableName, isBar));
   if (rc < 0) return (rc);
   
	rc = checkMOBError(mob_registerStatement(insertSQL(tableName, isBar)));
   if (rc < 0) return (rc);
   
   if (isBar)
      insertBar = rc;
   else
      insertTick = rc;
   
................................................................................
   tickData[1] = Bid;
   
   if (dt == lastTickTime && fraction <= lastTickFraction) {
      // Ensure the primary key is unique.
      fraction = lastTickFraction + 1;
   }
   
   int rc = checkMOBError(mob_insertTick(insertTick, dt, fraction, tickData));
   if (rc < 0) return (rc);
   lastTickTime = dt;
   lastTickFraction = fraction;

   return (0);
}

int startBar() {
   datetime dt = Time[1];
   
   if (lastBarTime < dt) {
      lastBarTime = dt;
      
      int rc = checkMOBError(insertBarAt(1));
      if (rc < 0) return (rc);
   }
   
   return (0);
}

int insertBarAt(int i) {
................................................................................
   barData[2] = Low[i];
   barData[3] = Close[i];
   barData[4] = Volume[i];

   int rc = mob_insertBar(insertBar, dt, barData);
   return (rc);
}


















































































<
<

<
<




|







 







|

|


|







 







|


|







 







|


|







 







|













|







 








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
22
23
24
25
26
27
28


29


30
31
32
33
34
35
36
37
38
39
40
41
..
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
..
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
...
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
...
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
...
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
int      mob_unregisterStatement(int stmtId);
int      mob_insertTick(int stmtId, datetime dt, int fraction, double vals[]);
int      mob_insertBar(int stmtId, datetime dt, double vals[]);
int      mob_copyRates(int stmtId, double rates[][6], int size, int start, int end);
double   mob_selectDouble(string sql, double defaultVal);
int      mob_selectInt(string sql, int defaultVal);
datetime mob_selectDatetime(string sql, datetime defaultVal);


string   getPeriodSymbol(int period_XX);


datetime mob_time();
#import

//---- input parameters
extern string    ExtDataSourceName = "testh2db";
extern string    ExtUsername       = "";
extern string    ExtPassword       = "";
extern string    ExtTablePrefix    = "MOB_";

int      insertTick;
int      insertBar;
datetime lastTickTime;
................................................................................
      return (-1);
   }
//----
   mob_create();
   int rc;
   
   if (ExtUsername == "")
      rc = mob_open(ExtDataSourceName, NULL, NULL);
   else
      rc = mob_open(ExtDataSourceName, ExtUsername, ExtPassword);
   if (rc < 0) return (rc);

   rc = mob_setAutoCommit(true);
   if (rc < 0) return (rc);
   
   // Prepare tick table
   string tickTable = ExtTablePrefix + getDefaultTableName(false);
   rc = prepareTable(tickTable, false);
   if (rc < 0) return (rc);
	
................................................................................
int deinit()
  {
//----
   // Insert the very last bar if the time passed enough.
   datetime serverTime = Time[0]; // Doesn't proceed on weekends.
   datetime currentTime = mob_time(); // Native time() API.
   if ((currentTime - serverTime) >= Period() * 60) {
      insertBarAt(0);
   }

   int rc = mob_close();
   if (rc < 0) return (rc);
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
................................................................................
   return(0);
  }
//+------------------------------------------------------------------+

int prepareTable(string tableName, bool isBar) {
   int rc;
   
   rc = createTableIfNotExists(tableName, isBar);
   if (rc < 0) return (rc);
   
	rc = mob_registerStatement(insertSQL(tableName, isBar));
   if (rc < 0) return (rc);
   
   if (isBar)
      insertBar = rc;
   else
      insertTick = rc;
   
................................................................................
   tickData[1] = Bid;
   
   if (dt == lastTickTime && fraction <= lastTickFraction) {
      // Ensure the primary key is unique.
      fraction = lastTickFraction + 1;
   }
   
   int rc = mob_insertTick(insertTick, dt, fraction, tickData);
   if (rc < 0) return (rc);
   lastTickTime = dt;
   lastTickFraction = fraction;

   return (0);
}

int startBar() {
   datetime dt = Time[1];
   
   if (lastBarTime < dt) {
      lastBarTime = dt;
      
      int rc = insertBarAt(1);
      if (rc < 0) return (rc);
   }
   
   return (0);
}

int insertBarAt(int i) {
................................................................................
   barData[2] = Low[i];
   barData[3] = Close[i];
   barData[4] = Volume[i];

   int rc = mob_insertBar(insertBar, dt, barData);
   return (rc);
}

int createTableIfNotExists(string tableName, bool isBar = true, bool drop = false) {
   int rc = 0;
 
   if (drop) rc = mob_execute("drop table " + tableName);
   
   rc = mob_selectInt("select count(*) from " + tableName, -1);
   bool exist = 0 <= rc;
   
   if (!exist) {
      if (isBar)
         rc = mob_execute(barTableSQL(tableName));
      else
         rc = mob_execute(tickTableSQL(tableName));
   }
   
   return (rc);
}

string barTableSQL(string tableName) {
   string sql;
   sql = "create table " + tableName + " ("
      + "  time timestamp"
      + ", open numeric(8, 5)"
      + ", high numeric(8, 5)"
      + ", low numeric(8, 5)"
      + ", close numeric(8, 5)"
      + ", volume double precision"
      + ", primary key (time)"
      + ")";
   return (sql);
}

string tickTableSQL(string tableName) {
   string sql;
   sql = "create table " + tableName + " ("
      + "  time timestamp"
      + ", fraction integer"
      + ", ask numeric(8, 5)"
      + ", bid numeric(8, 5)"
      + ", primary key (time, fraction)"
      + ")";
   return (sql);
}

string insertSQL(string tableName, bool isBar = true) {
   string sql;
   if (isBar)
      sql = insertBarSQL(tableName);
   else
      sql = insertTickSQL(tableName);
   return (sql);
}

string insertBarSQL(string tableName) {
   string sql;
   sql = "insert into " + tableName
      + " (time, open, high, low, close, volume) values (?, ?, ?, ?, ?, ?)";
   return (sql);
}

string insertTickSQL(string tableName) {
   string sql;
   sql = "insert into " + tableName
      + " (time, fraction, ask, bid) values (?, ?, ?, ?)";
   return (sql);
}

string getDefaultTableName(bool isBar = true) {
   if (isBar)
      return (Symbol() + "_" + getPeriodSymbol(Period()));
   else
      return (Symbol() + "_TICK");
}

Changes to experts/libraries/MT4ODBCBridge.dll.

cannot compute difference between binary files

Changes to experts/libraries/mt4odbcbridge.mq4.

6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
..
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184








185
186
187
188
189
190
191
...
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227



228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
...
366
367
368
369
370
371
372
373

374
375

376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397

398
399
400
401
402
403
404
405
406
407
408
409



410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
#property copyright "Osamu Nagano"
#property link      "http://www.google.com/profiles/onagano.g#about"
#property library

//+------------------------------------------------------------------+
//| Defines                                                          |
//+------------------------------------------------------------------+
#define RDBMS_GENERIC      0
#define RDBMS_MYSQL        1
#define RDBMS_POSTGRESQL   2

//+------------------------------------------------------------------+
//| DLL imports                                                      |
//+------------------------------------------------------------------+
#import "MT4ODBCBridge.dll"
int      MOB_create();
int      MOB_open(int conId, string dsn, string username, string password);
................................................................................
//| MOB wrapper functions                                            |
//+------------------------------------------------------------------+
void mob_create() {
   mob_conId = MOB_create();
}

int mob_open(string dsn, string username, string password) {
   return (MOB_open(mob_conId, dsn, username, password));
}

int mob_close() {
   return (MOB_close(mob_conId));
}

int mob_isDead() {
   return (MOB_isDead(mob_conId));
}

int mob_commit() {
   return (MOB_commit(mob_conId));
}

int mob_rollback() {
   return (MOB_rollback(mob_conId));
}

int mob_getAutoCommit() {
   return (MOB_getAutoCommit(mob_conId));
}

int mob_setAutoCommit(int autoCommit) {
   return (MOB_setAutoCommit(mob_conId, autoCommit));
}

int mob_execute(string sql) {
   return (MOB_execute(mob_conId, sql));
}

int mob_getLastErrorNo() {
   return (MOB_getLastErrorNo(mob_conId));
}

string mob_getLastErrorMesg() {
   return (MOB_getLastErrorMesg(mob_conId));
}

int mob_registerStatement(string sql) {
   return (MOB_registerStatement(mob_conId, sql));
}

int mob_unregisterStatement(int stmtId) {
   return (MOB_unregisterStatement(mob_conId, stmtId));
}

int mob_bindIntParameter(int stmtId, int stmtId, int slot, int intp[]) {
   return (MOB_bindIntParameter(mob_conId, stmtId, slot, intp));
}

int mob_bindDoubleParameter(int stmtId, int stmtId, int slot, double dblp[]) {
   return (MOB_bindDoubleParameter(mob_conId, stmtId, slot, dblp));
}

int mob_bindStringParameter(int stmtId, int stmtId, int slot, string strp) {
   return (MOB_bindStringParameter(mob_conId, stmtId, slot, strp));
}

int mob_bindDatetimeParameter(int stmtId, int stmtId, int slot, datetime dtp[]) {
   return (MOB_bindDatetimeParameter(mob_conId, stmtId, slot, dtp));
}

int mob_bindIntColumn(int stmtId, int stmtId, int slot, int intp[]) {
   return (MOB_bindIntColumn(mob_conId, stmtId, slot, intp));
}

int mob_bindDoubleColumn(int stmtId, int stmtId, int slot, double dblp[]) {
   return (MOB_bindDoubleColumn(mob_conId, stmtId, slot, dblp));
}

int mob_bindStringColumn(int stmtId, int stmtId, int slot, string strp) {
   return (MOB_bindStringColumn(mob_conId, stmtId, slot, strp));
}

int mob_bindDatetimeColumn(int stmtId, int stmtId, int slot, datetime dtp[]) {
   return (MOB_bindDatetimeColumn(mob_conId, stmtId, slot, dtp));
}

int mob_executeStatement(int stmtId) {
   return (MOB_executeStatement(mob_conId, stmtId));
}

int mob_selectToFetch(int stmtId) {
   return (MOB_selectToFetch(mob_conId, stmtId));
}

int mob_fetch(int stmtId) {
   return (MOB_fetch(mob_conId, stmtId));
}

int mob_fetchedAll(int stmtId) {
   return (MOB_fetchedAll(mob_conId, stmtId));
}

int mob_insertTick(int stmtId, datetime dt, int fraction, double vals[]) {
   return (MOB_insertTick(mob_conId, stmtId, dt, fraction, vals, ArraySize(vals)));
}

int mob_insertBar(int stmtId, datetime dt, double vals[]) {
   return (MOB_insertBar(mob_conId, stmtId, dt, vals, ArraySize(vals)));
}

int mob_copyRates(int stmtId, double rates[][6], int size, int start, int end) {
   return (MOB_copyRates(mob_conId, stmtId, rates, size, start, end));
}









double mob_selectDouble(string sql, double defaultVal) {
   return (MOB_selectDouble(mob_conId, sql, defaultVal));
}

int mob_selectInt(string sql, int defaultVal) {
   return (MOB_selectInt(mob_conId, sql, defaultVal));
}
................................................................................
//+------------------------------------------------------------------+
//| Stateful helper functions                                        |
//+------------------------------------------------------------------+
int checkMOBError(int rc, bool rollback = false, bool disconnect = false) {
   if (rc < 0) {
      int eno = mob_getLastErrorNo();
      string emesg = mob_getLastErrorMesg();
      Print("ERROR (", eno, "): ", emesg);
      if (rollback) mob_rollback();
      if (disconnect) mob_close();
   }
   return (rc);
}

int createTableIfNotExists(string tableName, bool isBar = true,
                       bool drop = false, int rdbms = RDBMS_GENERIC) {
   int rc = 0;
 



   if (drop) rc = mob_execute("drop table " + tableName);
   
   rc = mob_selectInt("select count(*) from " + tableName, -1);
   bool exist = 0 <= rc;
   
   switch (rdbms) {
   case RDBMS_GENERIC:
   default:
      if (!exist) {
         if (isBar)
            rc = mob_execute(barTableSQL(tableName, rdbms));
         else
            rc = mob_execute(tickTableSQL(tableName, rdbms));
      }
   }
   
   return (rc);
}

int timeDifference(string dsn, string username, string password) {
   datetime before = TimeCurrent();
   datetime after;
   mob_create();
   mob_open(dsn, username, password);
   string tableName = "mobtest_timedifference";
   createTableIfNotExists(tableName, true, true);
   int stmt = mob_registerStatement(insertBarSQL(tableName, RDBMS_GENERIC));
   double vals[5] = {0.0, 0.0, 0.0, 0.0, 0.0};
   mob_insertBar(stmt, before, vals);
   after = mob_selectDatetime("select time from " + tableName, 0);
   mob_execute("drop table " + tableName);
   mob_close();
   return (before - after);
}

//+------------------------------------------------------------------+
//| Stateless helper functions                                       |
//+------------------------------------------------------------------+
string barTableSQL(string tableName, int rdbms = RDBMS_GENERIC) {
   string sql;
   switch (rdbms) {
   case RDBMS_GENERIC:
   default:
      sql = "create table " + tableName + " ("
         + "  time timestamp"
         + ", open numeric(8, 5)"
         + ", high numeric(8, 5)"
         + ", low numeric(8, 5)"
         + ", close numeric(8, 5)"
         + ", volume double precision"
         + ", primary key (time)"
         + ")";
   }
   return (sql);
}

string tickTableSQL(string tableName, int rdbms = RDBMS_GENERIC) {
   string sql;
   switch (rdbms) {
   case RDBMS_GENERIC:
   default:
      sql = "create table " + tableName + " ("
         + "  time timestamp"
         + ", fraction integer"
         + ", ask numeric(8, 5)"
         + ", bid numeric(8, 5)"
         + ", primary key (time, fraction)"
         + ")";
   }
   return (sql);
}

string insertSQL(string tableName, bool isBar = true, int rdbms = RDBMS_GENERIC) {
   string sql;
   if (isBar)
      sql = insertBarSQL(tableName, rdbms);
   else
      sql = insertTickSQL(tableName, rdbms);
   return (sql);
}

string insertBarSQL(string tableName, int rdbms = RDBMS_GENERIC) {
   string sql;
   switch (rdbms) {
   case RDBMS_GENERIC:
   default:
      sql = "insert into " + tableName
         + " (time, open, high, low, close, volume) values (?, ?, ?, ?, ?, ?)";
   }
   return (sql);
}

string insertTickSQL(string tableName, int rdbms = RDBMS_GENERIC) {
   string sql;
   switch (rdbms) {
   case RDBMS_GENERIC:
   default:
      sql = "insert into " + tableName
         + " (time, fraction, ask, bid) values (?, ?, ?, ?)";
   }
   return (sql);
}

string getDefaultTableName(bool isBar = true) {
   if (isBar)
      return (Symbol() + "_" + getPeriodSymbol(Period()));
   else
      return (Symbol() + "_TICK");
}

string getPeriodSymbol(int period_XX) {
   if (period_XX == 0) period_XX = Period();
   switch (period_XX) {
   case PERIOD_M1:
      return ("M1");
      break;
   case PERIOD_M5:
      return ("M5");
      break;
................................................................................
      return ("MN1");
      break;
   default:
      return ("UNKNOWN");
   }
}

//+------------------------------------------------------------------+

//| Typical usecase functions                                        |
//+------------------------------------------------------------------+

int copyRatesLast(string dsn, string username, string password, string tableName, int lastBars) {
   int nBars = Bars;
   int start = nBars - lastBars;
   int end = nBars;
   return (copyRatesBetween(dsn, username, password, tableName, start, end));
}

int copyRates(string dsn, string username, string password, string tableName) {
   mob_create();
   mob_open(dsn, username, password);
   int count      = mob_selectInt("select count(*) from " + tableName, -1);
   datetime dtMax = mob_selectDatetime("select max(time) from " + tableName, -1);
   datetime dtMin = mob_selectDatetime("select min(time) from " + tableName, -1);
   int start;
   int end;
   int rv;
   mob_close();
   if (count <= 0) {
      start = 0;
      end = Bars - 1; // Exclude the latest bar.
      rv = copyRatesBetween(dsn, username, password, tableName, start, end);
      return (rv);

   } else {
      datetime dts[];
      int nBars = ArrayCopySeries(dts, MODE_TIME, NULL, 0);
      int iMax = ArrayBsearch(dts, dtMax, WHOLE_ARRAY, 0 , MODE_DESCEND);
      int iMin = ArrayBsearch(dts, dtMin, WHOLE_ARRAY, 0 , MODE_DESCEND);
      start = 0;
      end = nBars - (iMin + 1);
      rv += copyRatesBetween(dsn, username, password, tableName, start, end);
      start = nBars - iMax;
      end = nBars - 1; // Exclude the latest bar.
      rv += copyRatesBetween(dsn, username, password, tableName, start, end);
      return (rv);



   }
}

int copyRatesBetween(string dsn, string username, string password, string tableName, int start, int end) {
   if (!IsDllsAllowed()) {
      Alert("ERROR: [Allow DLL imports] NOT Checked.");
      return (-1);
   }

   if (start == end) return (0);
   if (start > end) {
      Print("Wrong indices. start ", start, " should be smaller than end ", end);
      return (-1);
   }
   if (start < 0) {
      Print("Start ", start, " cannot be smaller than zero");
      return (-1);
   }
   
   double rates[][6];
   int nBars = ArrayCopyRates(rates);
   if (nBars < 0) {
      int ec = GetLastError();
      Print("ArrayCopyRates causess ", ec, ", ", ErrorDescription(ec));
      return (nBars);
   }
   if (nBars < end) {
      Print("End index ", end,  " is larger than available size ", nBars);
      return (-1);
   }

   int rc = 0;
   int rv = 0;
   mob_create();
   
   rc = checkMOBError(mob_open(dsn, username, password), true, true);
   if (rc < 0) return (rc);
   
   rc = checkMOBError(mob_setAutoCommit(false), true, true);
   if (rc < 0) return (rc);

   rc = checkMOBError(createTableIfNotExists(tableName), true, true);
   if (rc < 0) return (rc);
   
   int insertTable = checkMOBError(mob_registerStatement(insertBarSQL(tableName)), true, true);
   if (rc < 0) return (rc);

   // RateInfo structure's order is OLHCV, which will be adjusted to OHLCV in database.
   rc = checkMOBError(mob_copyRates(insertTable, rates, ArraySize(rates), start, end), true, true);
   if (rc < 0) return (rc);
   rv = rc;

   rc = checkMOBError(mob_commit(), true, true);
   if (rc < 0) return (rc);

   rc = checkMOBError(mob_close(), true, true);
   if (rc < 0) return (rc);

   return(rv);
}
//+------------------------------------------------------------------+








<
<
<







 







|



|



|



|



|



|



|



|


<
<
<
<
<
<
<
<

|



|



|



|



|



|



|



|



|



|



|



|



|



|



|



|



|


>
>
>
>
>
>
>
>







 







|






|
<

|
>
>
>

|



<
<
<
|
<
|
<
<
<





<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<



<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<

<







 







<
>
|
<
>
|
|
|
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
>
|
<
<
<
<
<
<
<
<
<
<
<
>
>
>

<
<
<
<
<
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


6
7
8
9
10
11
12



13
14
15
16
17
18
19
..
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105








106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
...
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221

222
223
224
225
226
227
228
229
230
231



232

233



234
235
236
237
238
















239
240
241








































































242

243
244
245
246
247
248
249
...
269
270
271
272
273
274
275

276
277

278
279
280
281
282
283

















284
285











286
287
288
289





290
291




















































292
293
#property copyright "Osamu Nagano"
#property link      "http://www.google.com/profiles/onagano.g#about"
#property library

//+------------------------------------------------------------------+
//| Defines                                                          |
//+------------------------------------------------------------------+




//+------------------------------------------------------------------+
//| DLL imports                                                      |
//+------------------------------------------------------------------+
#import "MT4ODBCBridge.dll"
int      MOB_create();
int      MOB_open(int conId, string dsn, string username, string password);
................................................................................
//| MOB wrapper functions                                            |
//+------------------------------------------------------------------+
void mob_create() {
   mob_conId = MOB_create();
}

int mob_open(string dsn, string username, string password) {
   return (checkMOBError(MOB_open(mob_conId, dsn, username, password)));
}

int mob_close() {
   return (checkMOBError(MOB_close(mob_conId)));
}

int mob_isDead() {
   return (checkMOBError(MOB_isDead(mob_conId)));
}

int mob_commit() {
   return (checkMOBError(MOB_commit(mob_conId)));
}

int mob_rollback() {
   return (checkMOBError(MOB_rollback(mob_conId)));
}

int mob_getAutoCommit() {
   return (checkMOBError(MOB_getAutoCommit(mob_conId)));
}

int mob_setAutoCommit(int autoCommit) {
   return (checkMOBError(MOB_setAutoCommit(mob_conId, autoCommit)));
}

int mob_execute(string sql) {
   return (checkMOBError(MOB_execute(mob_conId, sql)));
}









int mob_registerStatement(string sql) {
   return (checkMOBError(MOB_registerStatement(mob_conId, sql)));
}

int mob_unregisterStatement(int stmtId) {
   return (checkMOBError(MOB_unregisterStatement(mob_conId, stmtId)));
}

int mob_bindIntParameter(int stmtId, int stmtId, int slot, int intp[]) {
   return (checkMOBError(MOB_bindIntParameter(mob_conId, stmtId, slot, intp)));
}

int mob_bindDoubleParameter(int stmtId, int stmtId, int slot, double dblp[]) {
   return (checkMOBError(MOB_bindDoubleParameter(mob_conId, stmtId, slot, dblp)));
}

int mob_bindStringParameter(int stmtId, int stmtId, int slot, string strp) {
   return (checkMOBError(MOB_bindStringParameter(mob_conId, stmtId, slot, strp)));
}

int mob_bindDatetimeParameter(int stmtId, int stmtId, int slot, datetime dtp[]) {
   return (checkMOBError(MOB_bindDatetimeParameter(mob_conId, stmtId, slot, dtp)));
}

int mob_bindIntColumn(int stmtId, int stmtId, int slot, int intp[]) {
   return (checkMOBError(MOB_bindIntColumn(mob_conId, stmtId, slot, intp)));
}

int mob_bindDoubleColumn(int stmtId, int stmtId, int slot, double dblp[]) {
   return (checkMOBError(MOB_bindDoubleColumn(mob_conId, stmtId, slot, dblp)));
}

int mob_bindStringColumn(int stmtId, int stmtId, int slot, string strp) {
   return (checkMOBError(MOB_bindStringColumn(mob_conId, stmtId, slot, strp)));
}

int mob_bindDatetimeColumn(int stmtId, int stmtId, int slot, datetime dtp[]) {
   return (checkMOBError(MOB_bindDatetimeColumn(mob_conId, stmtId, slot, dtp)));
}

int mob_executeStatement(int stmtId) {
   return (checkMOBError(MOB_executeStatement(mob_conId, stmtId)));
}

int mob_selectToFetch(int stmtId) {
   return (checkMOBError(MOB_selectToFetch(mob_conId, stmtId)));
}

int mob_fetch(int stmtId) {
   return (checkMOBError(MOB_fetch(mob_conId, stmtId)));
}

int mob_fetchedAll(int stmtId) {
   return (checkMOBError(MOB_fetchedAll(mob_conId, stmtId)));
}

int mob_insertTick(int stmtId, datetime dt, int fraction, double vals[]) {
   return (checkMOBError(MOB_insertTick(mob_conId, stmtId, dt, fraction, vals, ArraySize(vals))));
}

int mob_insertBar(int stmtId, datetime dt, double vals[]) {
   return (checkMOBError(MOB_insertBar(mob_conId, stmtId, dt, vals, ArraySize(vals))));
}

int mob_copyRates(int stmtId, double rates[][6], int size, int start, int end) {
   return (checkMOBError(MOB_copyRates(mob_conId, stmtId, rates, size, start, end)));
}

int mob_getLastErrorNo() {
   return (MOB_getLastErrorNo(mob_conId));
}

string mob_getLastErrorMesg() {
   return (MOB_getLastErrorMesg(mob_conId));
}

double mob_selectDouble(string sql, double defaultVal) {
   return (MOB_selectDouble(mob_conId, sql, defaultVal));
}

int mob_selectInt(string sql, int defaultVal) {
   return (MOB_selectInt(mob_conId, sql, defaultVal));
}
................................................................................
//+------------------------------------------------------------------+
//| Stateful helper functions                                        |
//+------------------------------------------------------------------+
int checkMOBError(int rc, bool rollback = false, bool disconnect = false) {
   if (rc < 0) {
      int eno = mob_getLastErrorNo();
      string emesg = mob_getLastErrorMesg();
      Print("MOB error #", eno, ": ", emesg);
      if (rollback) mob_rollback();
      if (disconnect) mob_close();
   }
   return (rc);
}

int createTableIfNotExists(string tableName, string sql, bool drop = false) {

   int rc = 0;

   // MySQL has 'CREATE TABLE IF NOT EXISTS ...'
   // while PostgreSQL has 'DROP TABLE IF EXISTS ...'
 
   if (drop) rc = mob_execute("drop table " + tableName);

   rc = mob_selectInt("select count(*) from " + tableName, -1);
   bool exist = 0 <= rc;
   



   if (!exist) {

      rc = mob_execute(sql);



   }
   
   return (rc);
}

















//+------------------------------------------------------------------+
//| Stateless helper functions                                       |
//+------------------------------------------------------------------+








































































string getPeriodSymbol(int period_XX) {

   switch (period_XX) {
   case PERIOD_M1:
      return ("M1");
      break;
   case PERIOD_M5:
      return ("M5");
      break;
................................................................................
      return ("MN1");
      break;
   default:
      return ("UNKNOWN");
   }
}


double getPipSize(string symbol) {
   double pip    = 0.0;

   double point  = MarketInfo(symbol, MODE_POINT);
   int    digits = MarketInfo(symbol, MODE_DIGITS);
   switch (digits) {
      case 5:
      case 3:
         pip = NormalizeDouble(point * 10, digits);

















         break;
      case 4:











      case 2:
         pip = NormalizeDouble(point, digits);
         break;
   }





   return (pip);
}




















































//+------------------------------------------------------------------+

Deleted experts/scripts/MOB_copyRates.mq4.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//+------------------------------------------------------------------+
//|                                                MOB_copyRates.mq4 |
//|                                                     Osamu Nagano |
//|                   http://www.google.com/profiles/onagano.g#about |
//+------------------------------------------------------------------+
#property copyright "Osamu Nagano"
#property link      "http://www.google.com/profiles/onagano.g#about"

#import "mt4odbcbridge.ex4"
string   getDefaultTableName();
int      copyRates(string dsn, string username, string password, string tableName);
#import

//+------------------------------------------------------------------+
//| script program start function                                    |
//+------------------------------------------------------------------+
int start()
  {
   if (!IsDllsAllowed()) {
      Alert("ERROR: [Allow DLL imports] NOT Checked.");
      return (-1);
   }
//----
   int rc = 0;
   string tableName = getDefaultTableName();
   
   rc = copyRates("testpostgresql", NULL, NULL, tableName);
//----
   return(rc);
  }
//+------------------------------------------------------------------+

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































Deleted experts/scripts/MOB_copyRatesBetween.mq4.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//+------------------------------------------------------------------+
//|                                         MOB_copyRatesBetween.mq4 |
//|                                                     Osamu Nagano |
//|                   http://www.google.com/profiles/onagano.g#about |
//+------------------------------------------------------------------+
#property copyright "Osamu Nagano"
#property link      "http://www.google.com/profiles/onagano.g#about"

#import "mt4odbcbridge.ex4"
string   getDefaultTableName();
int      copyRatesBetween(string dsn, string username, string password, string tableName, int start, int end);
#import

//---- input parameters
extern string    ExtDataSourceName = "fxddx";
extern string    ExtTablePrefix    = "MOB_";
extern string    ExtStartTime      = "2011.03.11 23:00:00";
extern string    ExtEndTime        = "2011.03.14 01:37:00";

//+------------------------------------------------------------------+
//| script program start function                                    |
//+------------------------------------------------------------------+
int start()
  {
   if (!IsDllsAllowed()) {
      Alert("ERROR: [Allow DLL imports] NOT Checked.");
      return (-1);
   }
//----
   int rc = 0;
   
   string dbName = ExtDataSourceName;
   Print("Database: ", dbName);
   
   string tableName = ExtTablePrefix + getDefaultTableName();
   Print("Table: ", tableName);
   
   datetime start = StrToTime(ExtStartTime);
   datetime end   = StrToTime(ExtEndTime);
   Print("Start: ", TimeToStr(start));
   Print("End  : ", TimeToStr(end));
   
   datetime dts[];
   int nBars  = ArrayCopySeries(dts, MODE_TIME, NULL, 0);
   int iStart = ArrayBsearch(dts, start, WHOLE_ARRAY, 0 , MODE_DESCEND);
   int iEnd   = ArrayBsearch(dts, end,   WHOLE_ARRAY, 0 , MODE_DESCEND);
   Print("Found s: ", TimeToStr(Time[iStart]));
   Print("Found e: ", TimeToStr(Time[iEnd]));
   
   int actualStart = nBars - iStart - 1;
   int actualEnd   = nBars - iEnd;

   rc = copyRatesBetween(dbName, NULL, NULL, tableName, actualStart, actualEnd);
//----
   return(rc);
  }
//+------------------------------------------------------------------+

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































































































Deleted experts/scripts/MOB_insertLastBar.mq4.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//+------------------------------------------------------------------+
//|                                            MOB_insertLastBar.mq4 |
//|                                                     Osamu Nagano |
//|                   http://www.google.com/profiles/onagano.g#about |
//+------------------------------------------------------------------+
#property copyright "Osamu Nagano"
#property link      "http://www.google.com/profiles/onagano.g#about"

#import "mt4odbcbridge.ex4"
void     mob_create();
int      mob_open(string dsn, string username, string password);
int      mob_close();
int      mob_registerStatement(string sql);
int      mob_insertBar(int stmtId, datetime dt, double vals[]);
int      checkMOBError(int rc);
string   getDefaultTableName(bool isBar = true);
string   insertSQL(string tableName, bool isBar = true);
#import

extern string    ExtDataSourceName = "fxddx";
extern string    ExtUsername       = "";
extern string    ExtPassword       = "";
extern string    ExtTablePrefix    = "MOB_";

//+------------------------------------------------------------------+
//| script program start function                                    |
//+------------------------------------------------------------------+
int start()
  {
//----
   string tableName = ExtTablePrefix + getDefaultTableName(true);
   Print("Target table name is ", tableName);

   mob_create();
   int rc;

   if (ExtUsername == "")
      rc = checkMOBError(mob_open(ExtDataSourceName, NULL, NULL));
   else
      rc = checkMOBError(mob_open(ExtDataSourceName, ExtUsername, ExtPassword));
   if (rc < 0) return (rc);

	rc = checkMOBError(mob_registerStatement(insertSQL(tableName, true)));
   if (rc < 0) return (rc);
   int insertBar = rc;

   int i = 0;
   double barData[5];
   datetime dt = Time[i];
   barData[0] = Open[i];
   barData[1] = High[i];
   barData[2] = Low[i];
   barData[3] = Close[i];
   barData[4] = Volume[i];

   rc = checkMOBError(mob_insertBar(insertBar, dt, barData));
   if (rc < 0) return (rc);

   rc = checkMOBError(mob_close());
   if (rc < 0) return (rc);
//----
   return(0);
  }
//+------------------------------------------------------------------+
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































































































Deleted experts/scripts/testMT4ODBCBridge.mq4.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//+------------------------------------------------------------------+
//|                                            testMT4ODBCBridge.mq4 |
//|                                                     Osamu Nagano |
//|                   http://www.google.com/profiles/onagano.g#about |
//+------------------------------------------------------------------+
#property copyright "Osamu Nagano"
#property link      "http://www.google.com/profiles/onagano.g#about"

#import "stdlib.ex4"
string   ErrorDescription(int error_code);
#import "mt4odbcbridge.ex4"
void     mob_create();
int      mob_open(string dsn, string username, string password);
int      mob_close();
int      mob_isDead();
int		mob_commit();
int		mob_rollback();
int		mob_getAutoCommit();
int		mob_setAutoCommit(int autoCommit);
int      mob_execute(string sql);
int      mob_getLastErrorNo();
string   mob_getLastErrorMesg();
int      mob_registerStatement(string sql);
int      mob_unregisterStatement(int stmtId);
int      mob_insertTick(int stmtId, datetime dt, int fraction, double vals[]);
int      mob_insertBar(int stmtId, datetime dt, double vals[]);
int      mob_copyRates(int stmtId, double rates[][6], int size, int start, int end);
double   mob_selectDouble(string sql, double defaultVal);
int      mob_selectInt(string sql, int defaultVal);
datetime mob_selectDatetime(string sql, datetime defaultVal);
string   insertBarSQL(string tableName);
string   insertTickSQL(string tableName);
int      checkMOBError(int rc);
int      createTableIfNotExists(string tableName);
int      timeDifference(string dsn, string username, string password);
string   getDefaultTableName();
string   getPeriodSymbol(int period_XX);
int      copyRates(string dsn, string username, string password, string tableName);
datetime mob_time();
datetime mob_localtime();
int      mob_strcpy(string dest, int size, string src);
#import

//+------------------------------------------------------------------+
//| script program start function                                    |
//+------------------------------------------------------------------+
int start()
  {
   int rc = 0;
   string dsName = "testpostgresql";
   string tableName = getDefaultTableName();
   
   rc = copyRates(dsName, NULL, NULL, tableName);
   
   datetime serverTime = TimeCurrent();
   Print("Server time is ", TimeToStr(serverTime));
   
   datetime nativeTime = mob_time();
   Print("Native time is ", TimeToStr(nativeTime));
   
   datetime localTime = mob_localtime();
   Print("Local time is ", TimeToStr(localTime));

   int timeDiff = timeDifference(dsName, NULL, NULL);
   Print("Time diff is ", timeDiff);
   
   mob_create();
   mob_open(dsName, NULL, NULL);
   datetime dtMax = mob_selectDatetime("select max(time) from " + tableName, -1);
   datetime dtMin = mob_selectDatetime("select min(time) from " + tableName, -1);
   mob_close();

   Print("Max date selected ", TimeToStr(dtMax));
   Print("Min date selected ", TimeToStr(dtMin));
   
   datetime dts[];
   ArrayCopySeries(dts, MODE_TIME, NULL, 0);
   int iMax = ArrayBsearch(dts, dtMax, WHOLE_ARRAY, 0 , MODE_DESCEND);
   int iMin = ArrayBsearch(dts, dtMin, WHOLE_ARRAY, 0 , MODE_DESCEND);

   Print("Selected indice max: ", iMax, " and min: ", iMin);
   Print("Max date ", TimeToStr(dts[iMax]));
   Print("Min date ", TimeToStr(dts[iMin]));
   Print("Bars ", Bars);
   
   return(rc);
  }
//+------------------------------------------------------------------+

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<