-
Notifications
You must be signed in to change notification settings - Fork 0
/
Blessing_3_v3.9.5-optimised.mq4
3496 lines (3307 loc) · 129 KB
/
Blessing_3_v3.9.5-optimised.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
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
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
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
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
472
473
474
475
476
477
478
479
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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
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
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
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
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//+---------------------------------------------------------------------+
//| Blessing 3 v3.9.5 |
//| May 29, 2011 |
//| Copyright ?2007-2011, J Talon LLC/FiFtHeLeMeNt |
//| In no event will authors be liable for any damages whatsoever. |
//| Use at your own risk. |
//| |
//| This EA is dedicated to Mike McKeough, a member of the Blessing |
//| Development Group, who passed away on Saturday, 31st July 2010. |
//| His contributions to the development of this EA have helped make |
//| it what it is today, and we will miss his enthusiasm, dedication |
//| and desire to make this the best EA possible. |
//| Rest In Peace. |
//+---------------------------------------------------------------------+
//http://www.forexbooknat.com/
//https://www.youtube.com/watch?v=NdU-8JqpMAI
#property copyright "Copyright ?2007-2011, J Talon LLC/FiFtHeLeMeNt"
#property link "http://www.jtatoday.com"
#property link "http://www.jtatoday.info/forum/index.php"
#include <stdlib.mqh>
#include <stderror.mqh>
#include <WinUser32.mqh>
#define A 1 //All (Basket + Hedge)
#define B 2 //Basket
#define H 3 //Hedge
#define T 4 //Ticket
#define P 5 //Pending
#define TREND_UP 0 /*趋势向上*/
#define TREND_DOWN 1 /*趋势向下*/
#define TREND_RANGE 2 /*区间*/
#define TREND_OFF 3 /*没有趋势*/
#define TRADE_OFF 0 /*0 = Off */
#define TRADE_BASE 1 /* will base entry on indicator */
#define TRADE_REVERSE 2 /* will trade in reverse */
#define NO_BASKET_ORDERS 0
#define NO_HEDGE_ORDERS 0
#define NO_BUY_STOP_ORDERS 0
#define NO_BUY_LIMIT_ORDERS 0
#define NO_SELL_STOP_ORDERS 0
#define NO_SELL_LIMIT_ORDERS 0
//2000
//+-----------------------------------------------------------------+
//| Extern parameters sets |
//+-----------------------------------------------------------------+
extern string TradeComment = "Blessing 3.9.5";
extern int EANumber = 1; // Enter a unique number to identify this EA
extern bool EmergencyCloseAll = false; // Setting this to true will close all open orders immediately
extern string LabelAcc = "Account Trading Settings:";
extern bool ShutDown = false; // Setting this to true will stop the EA trading after any open trades have been closed
extern double StopTradePercent = 10; // percent of account balance lost before trading stops
extern bool NanoAccount = false; // set to true for nano "penny a pip" account (contract size is $10,000)
extern double PortionPercentage = 100; // Percentage of account you want to trade on this pair
extern double MaxDrawDownPercentage = 50; // Percent of portion for max drawdown level. 最大回撤率
extern double MaxSpread = 5; // Maximum allowed spread while placing trades
extern bool UseHolidayShutdown = true; // Will shutdown over holiday period
extern string Holidays = "18/12-01/01"; // List of holidays, each seperated by a comma, [day]/[mth]-[day]/[mth], dates inclusive
extern bool PlaySounds = false; // will sound alarms
extern string AlertSound = "Alert.wav"; // Alarm sound to be played
extern string LabelIES = "Indicator / Entry Settings:";
extern bool B3Traditional = true; // Stop/Limits for entry if true, Buys/Sells if false
extern int ForceMarketCond = 3; // Market condition 0=uptrend 1=downtrend 2=range 3=off
extern bool UseAnyEntry = false; // true = ANY entry can be used to open orders, false = ALL entries used to open orders
extern int MAEntry = 1; // 0 = Off, 1 = will base entry on MA channel, 2 = will trade in reverse
extern int CCIEntry = 0; // 0 = Off, 1 = will base entry on CCI indicator, 2 = will trade in reverse
extern int BollingerEntry = 0; // 0 = Off, 1 = will base entry on BB, 2 = will trade in reverse
extern int StochEntry = 0; // 0 = Off, 1 = will base entry on Stoch, 2 = will trade in reverse
extern int MACDEntry = 0; // 0 = Off, 1 = will base entry on MACD, 2 = will trade in reverse
extern int MADiffEntry = 1; // 0 = Off, 1 = will base entry on MA Diff, 2 = will trade in reverse.
extern string LabelLS = "Lot Size Settings:";
extern bool UseMM = true; // Money Management
extern double LAF = 0.5; // Adjusts MM base lot for large accounts,Lot Adjustment Factor
extern double Lot = 0.01; // Starting lots if Money Management is off
extern double Multiplier = 1.4; // Multiplier on each level
extern string LabelGS = "Grid Settings:";
extern bool AutoCal = false; // Auto calculation of TakeProfit and Grid size;(自动计算赢利和网格大小)
extern double GAF = 1.0; // Widens/Squishes Grid on increments/decrements of .1
extern int EntryDelay = 2400; // Time Grid in seconds, to avoid opening of lots of levels in fast market
extern double EntryOffset = 5; // In pips, used in conjunction with logic to offset first trade entry
extern bool UseSmartGrid = true; // True = use RSI/MA calculation for next grid order
extern string LabelTS = "Trading Settings:";
extern int MaxTrades = 15; // Maximum number of trades to place (stops placing orders when reaches MaxTrades)
extern int BreakEvenTrade = 12; // Close All level, when reaches this level, doesn't wait for TP to be hit
extern double BEPlusPips = 2; // Pips added to Break Even Point before BE closure
extern bool UseCloseOldest = false; // True = will close the oldest open trade after CloseTradesLevel is reached
extern int CloseTradesLevel = 5; // will start closing oldest open trade at this level
extern int MaxCloseTrades = 4; // Maximum number of oldest trades to close
extern double CloseTPPips = 10; // After Oldest Trades have closed, Forces Take Profit to BE +/- xx Pips
extern double ForceTPPips = 0; // Force Take Profit to BE +/- xx Pips
extern double MinTPPips = 0; // Ensure Take Profit is at least BE +/- xx Pips
extern string LabelHS = "Hedge Settings:";
extern string HedgeSymbol = ""; // Enter the Symbol of the same/correlated pair EXACTLY as used by your broker.
extern int CorrPeriod = 30; // Number of days for checking Hedge Correlation
extern bool UseHedge = false; // Turns DD hedge on/off
extern string DDorLevel = "DD"; // DD = start hedge at set DD; Level = Start at set level
extern double HedgeStart = 20; // DD Percent or Level at which Hedge starts
extern double hLotMult = 0.8; // Hedge Lots = Open Lots * hLotMult
extern double hMaxLossPips = 30; // DD Hedge maximum pip loss - also hedge trailing stop
extern bool hFixedSL = false; // true = fixed SL at hMaxLossPips
extern double hTakeProfit = 30; // Hedge Take Profit
extern double hReEntryPC = 5; // Increase to HedgeStart to stop early re-entry of the hedge
extern bool StopTrailAtBE = true; // True = Trailing Stop will stop at BE; False = Hedge will continue into profit
extern bool ReduceTrailStop = true; // False = Trailing Stop is Fixed; True = Trailing Stop will reduce after BE is reached
extern string LabelES = "Exit Settings:";
extern bool MaximizeProfit = false; // Turns on TP move and Profit Trailing Stop Feature
extern double ProfitSet = 70; // Locks in Profit at this percent of Total Profit Potential
extern double MoveTP = 30; // Moves TP this amount in pips
extern int TotalMoves = 2; // Number of times you want TP to move before stopping movement
extern bool UseStopLoss = false; // Use Stop Loss and/or Trailing Stop Loss
extern double SLPips = 30; // Pips for fixed StopLoss from BE, 0=off
extern double TSLPips = 10; // Pips for trailing stop loss from BE + TSLPips: +ve = fixed trail; -ve = reducing trail; 0=off
extern double TSLPipsMin = 3; // Minimum trailing stop pips if using reducing TS
extern bool UsePowerOutSL = false; // Transmits a SL in case of internet loss
extern double POSLPips = 600; // Power Out Stop Loss in pips
extern bool UseFIFO = false; //
extern string LabelEE = "Early Exit Settings:";
extern bool UseEarlyExit = false; // Reduces ProfitTarget by a percentage over time and number of levels open
extern double EEStartHours = 3; // Number of Hours to wait before EE over time starts
extern bool EEFirstTrade = true; // true = StartHours from FIRST trade: false = StartHours from LAST trade
extern double EEHoursPC = 0.5; // Percentage reduction per hour (0 = OFF)
extern int EEStartLevel = 5; // Number of Open Trades before EE over levels starts
extern double EELevelPC = 10; // Percentage reduction at each level (0 = OFF)
extern bool EEAllowLoss = false; // true = Will allow the basket to close at a loss : false = Minimum profit is Break Even
extern string LabelAdv = "Advanced Settings Change sparingly";
extern string LabelGrid = "Grid Size Settings:";
extern string SetCountArray = "4,4"; // Specifies number of open trades in each block (separated by a comma)
extern string GridSetArray = "25,50,100"; // Specifies number of pips away to issue limit order (separated by a comma)
extern string TP_SetArray = "50,100,200"; // Take profit for each block (separated by a comma)
extern string LabelMA = "MA Entry Settings:";
extern int MAPeriod = 100; // Period of MA (H4 = 100, H1 = 400)
extern double MADistance = 10; // Distance from MA to be treated as Ranging Market
extern string LebelMADiff = "MA Diff Entry Settings";
extern int MAPeroid1 = 20;
extern int MAPeroid2 = 20;
extern int MAPeroid3 = 20;
extern int MAPeroid4 = 21;
extern int MAFilterUpL1 = 5;
extern int MAFilterUpL2 = 5;
extern int MAFilterUpL3 = 5;
extern int MAFilterUpL4 = 5;
extern int MAFiltrrUpLimitL1 = 10;
extern int MAFiltrrUpLimitL2 = 10;
extern int MAFiltrrUpLimitL3 = 10;
extern int MAFiltrrUpLimitL4 = 10;
extern int MAFilterDownL1 = -5;
extern int MAFilterDownL2 = -5;
extern int MAFilterDownL3 = -5;
extern int MAFilterDownL4 = -5;
extern int MAFiltrrDownLimitL1 = -10;
extern int MAFiltrrDownLimitL2 = -10;
extern int MAFiltrrDownLimitL3 = -10;
extern int MAFiltrrDownLimitL4 = -10;
extern double MAFactor = 1000;
extern double MAAngleFactor = 0.017453;
extern int MAPeroidPrivot = 114;
extern double MAUpRange = 0.1;
extern double MADownRange = -0.1;
extern string LabelCCI = "CCI Entry Settings:";
extern int CCIPeriod = 14; // Period for CCI calculation
extern string LabelBBS = "Bollinger Bands Entry Settings:";
extern int BollPeriod = 10; // Period for Bollinger
extern double BollDistance = 10; // Up/Down spread
extern double BollDeviation = 2.0; // Standard deviation multiplier for channel
extern string LabelSto = "Stochastic Entry Settings:";
extern int BuySellStochZone = 20; // Determines Overbought and Oversold Zones
extern int KPeriod = 10; // Stochastic KPeriod
extern int DPeriod = 2; // Stochastic DPeriod
extern int Slowing = 2; // Stochastic Slowing
extern string LabelMACD = "MACD Entry Settings:";
extern string LabelMACDTF = "0:Chart, 1:M1, 2:M5, 3:M15, 4:M30, 5:H1, 6:H4, 7:D1, 8:W1, 9:MN1";
extern int MACD_TF = 0; // Time frame for MACD calculation
extern int FastPeriod = 12; // MACD EMA Fast Period
extern int SlowPeriod = 26; // MACD EMA Slow Period
extern int SignalPeriod = 9; // MACD EMA Signal Period
extern int MACDPrice = 0; // 0=close, 1=open, 2=high, 3=low, 4=HL/2, 5=HLC/3 6=HLCC/4
extern string LabelSG = "Smart Grid Settings:";
extern string LabelSGTF = "0:Chart, 1:M1, 2:M5, 3:M15, 4:M30, 5:H1, 6:H4, 7:D1, 8:W1, 9:MN1";
extern int RSI_TF = 3; // Timeframe for RSI calculation - should be less than chart TF.
extern int RSI_Period = 14; // Period for RSI calculation
extern int RSI_Price = 0; // 0=close, 1=open, 2=high, 3=low, 4=HL/2, 5=HLC/3 6=HLCC/4
extern int RSI_MA_Period = 10; // Period for MA of RSI calculation
extern int RSI_MA_Method = 0; // 0=Simple MA, 1=Exponential MA, 2=Smoothed MA, 3=Linear Weighted MA
extern string LabelOS = "Other Settings:";
extern bool RecoupClosedLoss = true; // true = Recoup any Hedge/CloseOldest losses: false = Use original profit target.
extern int Level = 7; // Largest Assumed Basket size. Lower number = higher start lots
extern int slip = 99; // Adjusts opening and closing orders by "slipping" this amount
extern bool SaveStats = false; // true = will save equity statistics
extern int StatsPeriod = 3600; // seconds betwen stats entries - off by default
extern bool StatsInitialise = true; // true for backtest - false for foward/live to ACCUMULATE equity traces
extern string LabelUE = "Email Settings:";
extern bool UseEmail = false;
extern string LabelEDD = "At what DD% would you like Email warnings (Max: 49, Disable: 0)?";
extern double EmailDD1 = 20;
extern double EmailDD2 = 30;
extern double EmailDD3 = 40;
extern string LabelEH = "Number of hours before DD timer resets";
extern double EmailHours = 24; // Minimum number of hours between emails
extern string LabelDisplay = "Used to Adjust Overlay";
extern bool displayOverlay = true; // Turns the display on and off
extern bool displayLogo = true; // Turns off copyright and icon
extern bool displayCCI = true; // Turns off the CCI display
extern bool displayLines = true; // Show BE, TP and TS lines
extern int displayXcord = 100; // Moves display left and right
extern int displayYcord = 22; // Moves display up and down
extern int displayCCIxCord = 10; // Moves CCI display left and right
extern int displayFontSize = 9; // Changes size of display characters
extern int displaySpacing = 14; // Changes space between lines
extern double displayRatio = 1; // Ratio to increase label width spacing
extern color displayColor = DeepSkyBlue; // default color of display characters
extern color displayColorProfit = Green; // default color of profit display characters
extern color displayColorLoss = Red; // default color of loss display characters
extern color displayColorFGnd = White; // default color of ForeGround Text display characters
extern bool Debug = false; // Use to control debug msg
extern string LabelOpt = "These values can only be used while optimizing";
extern bool UseGridOpt = false; // Set to true if you want to be able to optimize the grid settings.
extern int SetArray1 = 4; // These values will replace the normal SetCountArray,
extern int SetArray2 = 4; // GridSetArray and TP_SetArray during optimization.
extern int SetArray3 = 0; // The default values are the same as the normal array defaults
extern int SetArray4 = 0;
extern int GridArray1 = 25; // REMEMBER:
extern int GridArray2 = 50; // There must be one more value for GridArray and TPArray
extern int GridArray3 = 100; // than there is for SetArray
extern int GridArray4 = 0;
extern int GridArray5 = 0;
extern int TPArray1 = 50;
extern int TPArray2 = 100;
extern int TPArray3 = 200;
extern int TPArray4 = 0;
extern int TPArray5 = 0;
//+-----------------------------------------------------------------+
//| Internal arguments set |
//+-----------------------------------------------------------------+
int ca;
int Magic; //Magic Number
int hMagic; //Hedge Magic Number Hedge:对冲
int CountOfBasketOrder; //Total count of basket order (buy+sell)
int CountOfPendingOrder; //Total count of pending order (bl+sl+ss+bs)
int CoundOfHedgeOrder; //Total count of hedge order (hedge buy + hedge sell)
double Pip,hPip;
int POSLCount;
double SLbL;
int Moves;
double MaxDD;
double SLb;
int AccountType;
double StopTradeBalance;/*该净值是,单子亏损导致净值达到这个时,停止交易*/
double InitialAB;/*EA开始运行时账户的净值*/
bool Testing,Visual;
bool AllowTrading;
bool EmergencyWarning;
double MaxDDPer;
int Error,y;
int Set1Level;
int Set2Level;
int Set3Level;
int Set4Level;
int EmailCount;
string StringTimeFrame;
datetime EmailSent;
int GridArray[,2];
double Lots[];
double MinLotSize;//交易商允许的最小交易手数
double LotStep; //交易手数的最小增量
double LotDecimal;//The lot decimal
int LotMult; //The Multiplier of the lots
int MinMult;
bool PendLot;
string CS,UAE;
int HolShutDown;
datetime HolArray[,4];
datetime HolFirst,HolLast,NextStats;
datetime OpenTimeBasketFirst; //Opentime of the first basket order
double RSI[];
int Digit[,2],TF[10]={0,1,5,15,30,60,240,1440,10080,43200};
double Email[3];
double EETime;
double PbC;
double PhC;
double hDDStart;
double ProfitBasketMax;//The max profit of basket order
double ProfitBasketMin;//The min profit of basket order
double ProfitHedgeMax;//The max profit of hedge order
double ProfitHedgeMin;//The min profit of hedge order
double LastClosedPL,ClosedPips,SLh,hLvlStart,StatLowEquity,StatHighEquity;
int hActive,EECount;
int TicketBasketFirst; //Ticket of the first basket order
int CbC,CaL,FileHandle;
bool TradesOpen;
bool FileClosed,HedgeTypeDD,hThisChart,hPosCorr,dLabels,FirstRun;
string FileName,ID,StatFile;
double TPb;
double StopLevel; //The broker stoplevel allowd
double TargetPips;
double LotsBaksetFirst;//Lots of the first basket order
double bTS;
// add by wujie.duan
/**
* @brief EA初始化函数
*
*
* @return
*/
int init()
{
CS="Waiting for next tick ."; // To display comments while testing, simply use CS = .... and
Comment(CS); // it will be displayed by the line at the end of the start() block.
CS="";
FirstRun=true;
AllowTrading=true;
if(EANumber<1)
EANumber=1;
if(Testing)
EANumber=0;
Magic=GenerateMagicNumber();
hMagic=JenkinsHash(Magic);
FileName="B3_"+Magic+".dat";
if(Debug){
Print("Magic Number: "+DTS(Magic,0));
Print("Hedge Number: "+DTS(hMagic,0));
Print("FileName: "+FileName);
}
Pip=Point;
if(Digits%2==1)Pip*=10;
if(NanoAccount)
AccountType=10;
else
AccountType=1;
MoveTP=ND(MoveTP*Pip,Digits);
EntryOffset=ND(EntryOffset*Pip,Digits);
MADistance=ND(MADistance*Pip,Digits);
BollDistance=ND(BollDistance*Pip,Digits);
POSLPips=ND(POSLPips*Pip,Digits);
hMaxLossPips=ND(hMaxLossPips*Pip,Digits);
hTakeProfit=ND(hTakeProfit*Pip,Digits);
CloseTPPips=ND(CloseTPPips*Pip,Digits);
ForceTPPips=ND(ForceTPPips*Pip,Digits);
MinTPPips=ND(MinTPPips*Pip,Digits);
BEPlusPips=ND(BEPlusPips*Pip,Digits);
SLPips=ND(SLPips*Pip,Digits);
TSLPips=ND(TSLPips*Pip,Digits);
TSLPipsMin=ND(TSLPipsMin*Pip,Digits);
slip*=Pip/Point;
if(UseHedge)
{ if(HedgeSymbol=="")HedgeSymbol=Symbol();
if(HedgeSymbol==Symbol())hThisChart=true;
else hThisChart=false;
hPip=MarketInfo(HedgeSymbol,MODE_POINT);
int hDigits=MarketInfo(HedgeSymbol,MODE_DIGITS);
if(hDigits%2==1)hPip*=10;
if(CheckCorr()>0.9||hThisChart)hPosCorr=true;
else if(CheckCorr()<-0.9)hPosCorr=false;
else
{ AllowTrading=false;
UseHedge=false;
Print("The Hedge Symbol you have entered ("+HedgeSymbol+") is not closely correlated to "+Symbol());
}
if(StringSubstr(DDorLevel,0,1)=="D"||StringSubstr(DDorLevel,0,1)=="d")HedgeTypeDD=true;
else if(StringSubstr(DDorLevel,0,1)=="L"||StringSubstr(DDorLevel,0,1)=="l")HedgeTypeDD=false;
else UseHedge=false;
if(HedgeTypeDD)
{ HedgeStart/=100;
hDDStart=HedgeStart;
}
}
StopTradePercent/=100;
ProfitSet/=100;
EEHoursPC/=100;
EELevelPC/=100;
hReEntryPC/=100;
PortionPercentage/=100;
InitialAB=AccountBalance();
StopTradeBalance=InitialAB*(1-StopTradePercent);
Testing=IsTesting();
Visual=IsVisualMode();
if(Testing)
ID="B3Test.";
else
ID=DTS(Magic,0)+".";
HideTestIndicators(true);
MinLotSize=MarketInfo(Symbol(),MODE_MINLOT);
if(MinLotSize>Lot)
{ Print("Lot is less than your brokers minimum lot size");
AllowTrading=false;
}
LotStep=MarketInfo(Symbol(),MODE_LOTSTEP);
double MinLot=MathMin(MinLotSize,LotStep);
LotMult=ND(MathMax(Lot,MinLotSize)/MinLot,0);
MinMult=LotMult;
Lot=MinLot;
if(MinLot<0.01)LotDecimal=3;
else if(MinLot<0.1)LotDecimal=2;
else if(MinLot<1)LotDecimal=1;
else LotDecimal=0;
FileHandle=FileOpen(FileName,FILE_BIN|FILE_READ);
if(FileHandle!=-1)
{ TicketBasketFirst=FileReadInteger(FileHandle,LONG_VALUE);
FileClose(FileHandle);
Error=GetLastError();
if(OrderSelect(TicketBasketFirst,SELECT_BY_TICKET))
{ if(OrderCloseTime()==0)
{ OpenTimeBasketFirst=OrderOpenTime();
LotsBaksetFirst=OrderLots();
LotMult=MathMax(1,LotsBaksetFirst/MinLot);
PbC=FindClosedPL(B);
PhC=FindClosedPL(H);
TradesOpen=true;
if(Debug)Print(FileName+" File Read: "+TicketBasketFirst+" Lots: "+DTS(LotsBaksetFirst,LotDecimal));
}
else
bool DeleteFile=true;
}
else DeleteFile=true;
if(DeleteFile)
{ FileDelete(FileName);
TicketBasketFirst=0;
OpenTimeBasketFirst=0;
LotsBaksetFirst=0;
Error=GetLastError();
if(Error==ERR_NO_ERROR)
{ if(Debug)Print(FileName+" File Deleted");
}
else Print("Error deleting file: "+FileName+" "+Error+" "+ErrorDescription(Error));
}
}
GlobalVariableSet(ID+"LotMult",LotMult);
if(Debug)
Print("Lot Decimal: "+DTS(LotDecimal,0));
EmergencyWarning=EmergencyCloseAll;
if(IsOptimization())Debug=false;
if(UseAnyEntry)UAE="||";
else UAE="&&";
//参数检查,设置错了参数将使用默认参数
if(ForceMarketCond<0||ForceMarketCond>3)
ForceMarketCond=3;
if(MAEntry<0||MAEntry>2)
MAEntry=TRADE_OFF;
if(CCIEntry<0||CCIEntry>2)
CCIEntry=TRADE_OFF;
if(BollingerEntry<0||BollingerEntry>2)
BollingerEntry=0;
if(StochEntry<0||StochEntry>2)
StochEntry=TRADE_OFF;
if(MACDEntry<0||MACDEntry>2)
MACDEntry=TRADE_OFF;
if(MaxCloseTrades==0)
MaxCloseTrades=MaxTrades;
ArrayResize(Digit,6);
for(y=0;y<ArrayRange(Digit,0);y++)
{ if(y>0)Digit[y,0]=MathPow(10,y);
Digit[y,1]=y;
if(Debug)Print("Digit: "+y+" ["+Digit[y,0]+","+Digit[y,1]+"]");
}
LabelCreate();
dLabels=false;
//+-----------------------------------------------------------------+
//| Set Lot Array |
//+-----------------------------------------------------------------+
ArrayResize(Lots,MaxTrades);
if(Debug)
Print("Lot Multiplier: "+LotMult);
for(y=0;y<MaxTrades;y++)
{
if(y==0||Multiplier<1)
Lots[y]=Lot;
else
Lots[y]=ND(MathMax(Lots[y-1]*Multiplier,Lots[y-1]+LotStep),LotDecimal);
if(Debug)
Print("Lot Size for level "+DTS(y+1,0)+" : "+DTS(Lots[y]*MathMax(LotMult,1),LotDecimal));
}
/*
* LotStep = 0.01
* Multiplier = 1.4
*
* Lots[0-14] ={
* 0.01,0.02,0.03,0.04,0.05,
* 0.07,0.09,0.12,0.16,0.22,
* 0.30,0.42,0.58,0.81,1.13
* }
*
*/
if(Multiplier<1)
Multiplier=1;
/* GridArray[15][2]
*
* [25,50] [25,50] [25,50] [25,50]
* [50,100] [50,100] [50,100] [50,100]
* [100,200] [100,200] [100,200] [100,200]
* [100,200] [100,200] [100,200]
*/
//+-----------------------------------------------------------------+
//| Set Grid and TP array |
//+-----------------------------------------------------------------+
if(!AutoCal)
{ int GridSet,GridTemp,GridTP,GridIndex,GridLevel,GridError;
ArrayResize(GridArray,MaxTrades);
if(IsOptimization()&&UseGridOpt)
{//Returns true if Expert Advisor runs in the Strategy Tester optimization mode, otherwise returns false.
if(SetArray1>0)
{ SetCountArray=DTS(SetArray1,0);
GridSetArray=DTS(GridArray1,0);
TP_SetArray=DTS(TPArray1,0);
}
if(SetArray2>0||(SetArray1>0&&GridArray2>0))
{ if(SetArray2>0)SetCountArray=SetCountArray+","+DTS(SetArray2,0);
GridSetArray=GridSetArray+","+DTS(GridArray2,0);
TP_SetArray=TP_SetArray+","+DTS(TPArray2,0);
}
if(SetArray3>0||(SetArray2>0&&GridArray3>0))
{ if(SetArray3>0)SetCountArray=SetCountArray+","+DTS(SetArray3,0);
GridSetArray=GridSetArray+","+DTS(GridArray3,0);
TP_SetArray=TP_SetArray+","+DTS(TPArray3,0);
}
if(SetArray4>0||(SetArray3>0&&GridArray4>0))
{ if(SetArray4>0)SetCountArray=SetCountArray+","+DTS(SetArray4,0);
GridSetArray=GridSetArray+","+DTS(GridArray4,0);
TP_SetArray=TP_SetArray+","+DTS(TPArray4,0);
}
if(SetArray4>0&&GridArray5>0)
{ GridSetArray=GridSetArray+","+DTS(GridArray5,0);
TP_SetArray=TP_SetArray+","+DTS(TPArray5,0);
}
}
while(GridIndex<MaxTrades)
{ if(StringFind(SetCountArray,",")==-1&&GridIndex==0)
{ GridError=1;
break;
}
else
GridSet=StrToInteger(StringSubstr(SetCountArray,0,StringFind(SetCountArray,",")));
if(GridSet>0)
{
SetCountArray=StringSubstr(SetCountArray,StringFind(SetCountArray,",")+1);
GridTemp=StrToInteger(StringSubstr(GridSetArray,0,StringFind(GridSetArray,",")));
GridSetArray=StringSubstr(GridSetArray,StringFind(GridSetArray,",")+1);
GridTP=StrToInteger(StringSubstr(TP_SetArray,0,StringFind(TP_SetArray,",")));
TP_SetArray=StringSubstr(TP_SetArray,StringFind(TP_SetArray,",")+1);
}
else
GridSet=MaxTrades;
if(GridTemp==0||GridTP==0)
{ GridError=2;
break;
}
for(GridLevel=GridIndex;GridLevel<=MathMin(GridIndex+GridSet-1,MaxTrades-1);GridLevel++)
{
GridArray[GridLevel,0]=GridTemp;
GridArray[GridLevel,1]=GridTP;
if(Debug)
Print("GridArray "+(GridLevel+1)+" : ["+GridArray[GridLevel,0]+","+GridArray[GridLevel,1]+"]");
}
GridIndex=GridLevel;
}
if(GridError>0||GridArray[0,0]==0||GridArray[0,1]==0)
{ if(GridError==1)Print("Grid Array Error. Each value should be separated by a comma.");
else Print("Grid Array Error. Check that there is one more 'Grid' and 'TP' number than there are 'Set' numbers, separated by commas.");
AllowTrading=false;
}
}
else
{ while(GridIndex<4)
{
GridSet=StrToInteger(StringSubstr(SetCountArray,0,StringFind(SetCountArray,",")));
SetCountArray=StringSubstr(SetCountArray,StringFind(SetCountArray,DTS(GridSet,0))+2);
if(GridIndex==0&&GridSet<1)
{ GridError=1;
break;
}
if(GridSet>0)
GridLevel+=GridSet;
else if(GridLevel<MaxTrades)
GridLevel=MaxTrades;
else
GridLevel=MaxTrades+1;
if(GridIndex==0)
Set1Level=GridLevel;
else if(GridIndex==1&&GridLevel<=MaxTrades)
Set2Level=GridLevel;
else if(GridIndex==2&&GridLevel<=MaxTrades)
Set3Level=GridLevel;
else if(GridIndex==3&&GridLevel<=MaxTrades)
Set4Level=GridLevel;
GridIndex++;
}
if(GridError==1||Set1Level==0)
{ Print("Error setting up the Grid Levels. Check that the SetCountArray has valid numbers, separated by a comma.");
AllowTrading=false;
}
}
//+-----------------------------------------------------------------+
//| Set holidays array |
//+-----------------------------------------------------------------+
if(UseHolidayShutdown)
{ int HolTemp,NumHols,NumBS,HolCounter;
string HolTempStr;
if(StringFind(Holidays,",",0)==-1)NumHols=1;
else
{ NumHols=1;
while(HolTemp!=-1)
{ HolTemp=StringFind(Holidays,",",HolTemp+1);
if(HolTemp!=-1)NumHols+=1;
}
}
HolTemp=0;
while(HolTemp!=-1)
{ HolTemp=StringFind(Holidays,"/",HolTemp+1);
if(HolTemp!=-1)NumBS+=1;
}
if(NumBS!=NumHols*2)
{ Print("Holidays Error, number of back-slashes ("+NumBS+") should be equal to 2* number of Holidays ("+NumHols+
", and separators should be a comma.");
AllowTrading=false;
}
else
{ HolTemp=0;
ArrayResize(HolArray,NumHols);
while(HolTemp!=-1)
{ if(HolTemp==0)HolTempStr=StringTrimLeft(StringTrimRight(StringSubstr(Holidays,0,StringFind(Holidays,",",HolTemp))));
else HolTempStr=StringTrimLeft(StringTrimRight(StringSubstr(Holidays,HolTemp+1,
StringFind(Holidays,",",HolTemp+1)-StringFind(Holidays,",",HolTemp)-1)));
HolTemp=StringFind(Holidays,",",HolTemp+1);
HolArray[HolCounter,0]=StrToInteger(StringSubstr(StringSubstr(HolTempStr,0,StringFind(HolTempStr,"-",0)),
StringFind(StringSubstr(HolTempStr,0,StringFind(HolTempStr,"-",0)),"/")+1));
HolArray[HolCounter,1]=StrToInteger(StringSubstr(StringSubstr(HolTempStr,0,StringFind(HolTempStr,"-",0)),0,
StringFind(StringSubstr(HolTempStr,0,StringFind(HolTempStr,"-",0)),"/")));
HolArray[HolCounter,2]=StrToInteger(StringSubstr(StringSubstr(HolTempStr,StringFind(HolTempStr,"-",0)+1),
StringFind(StringSubstr(HolTempStr,StringFind(HolTempStr,"-",0)+1),"/")+1));
HolArray[HolCounter,3]=StrToInteger(StringSubstr(StringSubstr(HolTempStr,StringFind(HolTempStr,"-",0)+1),0,
StringFind(StringSubstr(HolTempStr,StringFind(HolTempStr,"-",0)+1),"/")));
HolCounter+=1;
}
}
for(HolTemp=0;HolTemp<HolCounter;HolTemp++)
{ int Start1,Start2,Temp0,Temp1,Temp2,Temp3;
for(int Item1=HolTemp+1;Item1<HolCounter;Item1++)
{ Start1=HolArray[HolTemp,0]*100+HolArray[HolTemp,1];
Start2=HolArray[Item1,0]*100+HolArray[Item1,1];
if(Start1>Start2)
{ Temp0=HolArray[Item1,0];
Temp1=HolArray[Item1,1];
Temp2=HolArray[Item1,2];
Temp3=HolArray[Item1,3];
HolArray[Item1,0]=HolArray[HolTemp,0];
HolArray[Item1,1]=HolArray[HolTemp,1];
HolArray[Item1,2]=HolArray[HolTemp,2];
HolArray[Item1,3]=HolArray[HolTemp,3];
HolArray[HolTemp,0]=Temp0;
HolArray[HolTemp,1]=Temp1;
HolArray[HolTemp,2]=Temp2;
HolArray[HolTemp,3]=Temp3;
}
}
}
if(Debug)
{ for(HolTemp=0;HolTemp<HolCounter;HolTemp++)
Print("Holidays - From: ",HolArray[HolTemp,1],"/",HolArray[HolTemp,0]," - ",HolArray[HolTemp,3],"/",HolArray[HolTemp,2]);
}
}
//+-----------------------------------------------------------------+
//| Set email parameters |
//+-----------------------------------------------------------------+
if(UseEmail)
{
if(Period()==PERIOD_MN1)StringTimeFrame="MN1";
else if(Period()==PERIOD_W1)StringTimeFrame="W1";
else if(Period()==PERIOD_D1)StringTimeFrame="D1";
else if(Period()==PERIOD_H4)StringTimeFrame="H4";
else if(Period()==PERIOD_H1)StringTimeFrame="H1";
else if(Period()==PERIOD_M30)StringTimeFrame="M30";
else if(Period()==PERIOD_M15)StringTimeFrame="M15";
else if(Period()==PERIOD_M5)StringTimeFrame="M5";
else if(Period()==PERIOD_M1)StringTimeFrame="M1";
Email[0]=MathMax(MathMin(EmailDD1,MaxDrawDownPercentage-1),0)/100;
Email[1]=MathMax(MathMin(EmailDD2,MaxDrawDownPercentage-1),0)/100;
Email[2]=MathMax(MathMin(EmailDD3,MaxDrawDownPercentage-1),0)/100;
ArraySort(Email,WHOLE_ARRAY,0,MODE_ASCEND);
for(int z=0;z<=2;z++)
{ for(y=0;y<=2;y++)
{ if(Email[y]==0)
{ Email[y]=Email[y+1];
Email[y+1]=0;
}
}
if(Debug)Print("Email ["+(z+1)+"] : "+Email[z]);
}
}
//+-----------------------------------------------------------------+
//| Set SmartGrid parameters |
//+-----------------------------------------------------------------+
if(UseSmartGrid)
{ ArrayResize(RSI,RSI_Period+RSI_MA_Period);
ArraySetAsSeries(RSI,true);
}
//+---------------------------------------------------------------+
//| Initialize Statistics |
//+---------------------------------------------------------------+
StatFile=Symbol()+"-"+Period()+"-"+EANumber+".csv";
if(SaveStats)
{ StatFile=Symbol()+"-"+Period()+"-"+EANumber+".csv";
NextStats=TimeCurrent();
Stats(StatsInitialise,false,AccountBalance()*PortionPercentage,0);
}
return(0);
}
// add by wujie.duan
/**
* @brief EA退出时,清理函数
*
*
* @return
*/
int deinit()
{ switch(UninitializeReason())
{ case REASON_REMOVE:
case REASON_CHARTCLOSE:
case REASON_CHARTCHANGE:
if(CountOfPendingOrder>0)while(CountOfPendingOrder>0)CountOfPendingOrder-=ExitTrades(P,displayColorLoss,"Blessing Removed");
GlobalVariablesDeleteAll(ID);
case REASON_RECOMPILE:
case REASON_PARAMETERS:
case REASON_ACCOUNT:
if(!Testing)LabelDelete();
Comment("");
}
return(0);
}
// add by wujie.duan
/**
* @brief EA开始函数
*
*
* @return
*/
int start()
{
int count_of_buy_limit =0; // Total count of buy limit
int count_of_sell_limit =0; // Total count of sell limit
int count_of_buy_stop =0; // Total count of buy stop
int count_of_sell_stop =0; // Total count of sell stop
double total_lots_of_basket_order =0; // Total lots of basket order(buy+sell)
double open_price_buy_limit =0; // Buy limit open price
double open_price_sell_limit =0; // Sell limit open price
double stoploss_of_busket_buy_order =0; // stop losses are set to zero if POSL off
double stoploss_of_busket_sell_order =0; // stop losses are set to zero if POSL off
double broker_costs_of_basket_order =0; // Broker costs of basket order
double broker_costs_of_hedge_order =0; // Broker costs of hedge order
double BCa =0; // Broker costs (swap + commission) [basket + hedge]
double ProfitPot =0; // The Potential Profit of a basket of Trades
double PipValue,PipVal2;
double OrderLot;
double g2,tp2,Entry,RSI_MA;
double total_lots_of_hedge_order; //Total lots of hedge order
int Ticket;
int IndEntry; //The indicator entry count
double PaC,ProfitBasketPips,PbTarget;
double DrawDownPercentage; //Percent of portion for drawdown level
double BEbasket;
double BEhedge;
double BEa;
bool BuyMe;
bool SellMe,Success;
bool SetPOSL;
string IndicatorUsed;
/*The hedge's var */
double profit_of_hedge_order; // Total profit of hedge order (hedge sell profit + hedge buy profit)
int count_of_hedge_buy_order = 0; // Count of hedge buy order
int count_of_hedge_sell_order = 0; // Count of hedge sell order
double total_lots_of_hedge_buy_order; // Total lots of hedge buy order
double total_lots_of_hedge_sell_order; // Total lots of hedge sell order
double OThO; // Opentime of the first hedge order
double ThO; // Ticket of the first hedge order
double OPhO; // Openprice of the first hedge order
/*The basket's var */
double profit_of_basket_order; // Total profit of basket order (sell+buy-hedge)
int count_of_basket_buy_order = 0; // Count of basket buy order
int count_of_basket_sell_order = 0; // Count of basket sell order
int open_time_basket_last; // Opentime of the last basket order
double open_price_basket_last; // Openprice of the last basket order
double OTbO; // Opentime of the first basket order
double TbO; // Ticket of the first basket order
double OPbO; // Openprice of the first basket order
double total_lots_of_busket_buy_order = 0; // Total lots of basket buy order
double total_lots_of_busket_sell_order = 0; // Total lots of basket sell order
//+-----------------------------------------------------------------+
//| Count Open Orders, Lots and Totals |
//+-----------------------------------------------------------------+
PipValue=MarketInfo(Symbol(),MODE_TICKVALUE)/MarketInfo(Symbol(),MODE_TICKSIZE)*Pip;
PipVal2=PipValue/Pip;
StopLevel=MarketInfo(Symbol(),MODE_STOPLEVEL)*Point;
for(y=0;y<OrdersTotal();y++)
{
if(!OrderSelect(y,SELECT_BY_POS,MODE_TRADES))
continue;
int Type=OrderType();
if(OrderMagicNumber()==hMagic) //Process the hedge order
{
/*profit_of_hedge_order:Profit of hedge */
profit_of_hedge_order+=OrderProfit();/*OrderProfit:当前选中,订单的利润*/
broker_costs_of_hedge_order+=OrderSwap()+OrderCommission();/*OrderSwap:返回掉期值,OrderCommission() - 获取订单佣金*/
BEhedge+=OrderLots()*OrderOpenPrice(); /*开仓价格*当前订单的手数*/
if(OrderOpenTime()<OThO||OThO==0)
{
OThO=OrderOpenTime();
ThO=OrderTicket();
OPhO=OrderOpenPrice();
}
if(Type==OP_BUY)
{
count_of_hedge_buy_order++;
total_lots_of_hedge_buy_order+=OrderLots();
}
else if(Type==OP_SELL)
{ count_of_hedge_sell_order++;
total_lots_of_hedge_sell_order+=OrderLots();
}
continue;
}
if(OrderMagicNumber()!=Magic||OrderSymbol()!=Symbol())
continue;
if(OrderTakeProfit()>0)
ModifyOrder(OrderOpenPrice(),OrderStopLoss());
if(Type<=OP_SELL)
{
profit_of_basket_order+=OrderProfit();/*profit_of_basket_order:非对冲单总的利润*/
broker_costs_of_basket_order+=OrderSwap()+OrderCommission(); /* 过夜费 + 佣金 */
BEbasket+=OrderLots()*OrderOpenPrice();
if(OrderOpenTime()>=open_time_basket_last)
{ open_time_basket_last=OrderOpenTime();
open_price_basket_last=OrderOpenPrice();
}
if(OrderOpenTime()<OpenTimeBasketFirst||TicketBasketFirst==0)
{ OpenTimeBasketFirst=OrderOpenTime();
TicketBasketFirst=OrderTicket();
LotsBaksetFirst=OrderLots();
}
if(OrderOpenTime()<OTbO||OTbO==0)
{ OTbO=OrderOpenTime();
TbO=OrderTicket();
OPbO=OrderOpenPrice();
}
if(UsePowerOutSL&&(POSLPips>0&&OrderStopLoss()==0)||(POSLPips==0&&OrderStopLoss()>0))
SetPOSL=true;
if(Type==OP_BUY)
{ count_of_basket_buy_order++;
total_lots_of_busket_buy_order+=OrderLots();
continue;
}
else
{ count_of_basket_sell_order++;
total_lots_of_busket_sell_order+=OrderLots();
continue;
}
}
else
{ if(Type==OP_BUYLIMIT)
{ count_of_buy_limit++;
open_price_buy_limit=OrderOpenPrice();
continue;
}
else if(Type==OP_SELLLIMIT)
{ count_of_sell_limit++;
open_price_sell_limit=OrderOpenPrice();
continue;
}
else if(Type==OP_BUYSTOP)count_of_buy_stop++;
else count_of_sell_stop++;
}
}
CountOfBasketOrder=count_of_basket_buy_order+count_of_basket_sell_order;
total_lots_of_basket_order=total_lots_of_busket_buy_order+total_lots_of_busket_sell_order;
profit_of_basket_order=ND(profit_of_basket_order+broker_costs_of_basket_order,2);
CoundOfHedgeOrder=count_of_hedge_buy_order+count_of_hedge_sell_order;
total_lots_of_hedge_order=total_lots_of_hedge_buy_order+total_lots_of_hedge_sell_order;
profit_of_hedge_order=ND(profit_of_hedge_order+broker_costs_of_hedge_order,2);
CountOfPendingOrder=count_of_buy_limit+count_of_sell_limit+count_of_buy_stop+count_of_sell_stop; /* Total count of pending order */
BCa=broker_costs_of_basket_order+broker_costs_of_hedge_order;/*总的交易商手续费*/
//+-----------------------------------------------------------------+
//| Calculate Min/Max Profit and Break Even Points |
//+-----------------------------------------------------------------+
if(total_lots_of_basket_order>0)/*Basket lots >0*/
{
BEbasket=ND(BEbasket/total_lots_of_basket_order,Digits);/*计算平均开仓价格*/
if(BCa<0)
BEbasket-=ND(BCa/PipVal2/(total_lots_of_busket_buy_order-total_lots_of_busket_sell_order),Digits);/* 交易商倒给钱的情况*/
if(profit_of_basket_order>ProfitBasketMax||ProfitBasketMax==0)
ProfitBasketMax=profit_of_basket_order;
if(profit_of_basket_order<ProfitBasketMin||ProfitBasketMin==0)
ProfitBasketMin=profit_of_basket_order;
if(!TradesOpen)/*EA没有开单,只是统计*/
{
FileHandle=FileOpen(FileName,FILE_BIN|FILE_WRITE);
if(FileHandle>-1)
{ FileWriteInteger(FileHandle,TicketBasketFirst);
FileClose(FileHandle);
TradesOpen=true;
if(Debug)Print(FileName+" File Written: "+TicketBasketFirst);
}
}
}
else if(TradesOpen)
{
TPb=0;
ProfitBasketMax=0;
ProfitBasketMin=0;
OpenTimeBasketFirst=0;
TicketBasketFirst=0;
LotsBaksetFirst=0;