☞ 스위스의 유로에 대한 스위스 프랑의 PEG제를 이용하여 EURUSD와 USDCHF간 역의 상관관계에 의거 EURUSD EA에서 발생한 신호를 USDCHF에서 역으로 진입하는 전략(기본 EURUSD 5분봉을 이용)

 

//******************************************************************************
//|                                                          UsdChf_Guri_V0.1  |
//|                                             Copyright @ 2012 Gguri FX LAB  |
//******************************************************************************

/*
Time Frame : M15
Pairs : USDCHF
Based Indicator : MA, CCI, Stochastic, WPR, ATR
Start Date : 2012-11-10
Logic : 
Attach : M5 
EAs : 4개 개별 EA의 통합EA

//******************************************************************************
//| Version History                                                            |
//******************************************************************************

Version 0.1
- Day Filter수정
- Money Management 기능추가
- 오류처리 기능강화
- Money Management 기능강화
- 총 매매건수 < MaxTrades
- MaxTrades 선택 기능 추가
- Test나 최적화시 부하감소(화면표시 이전 Exit)
- Close정보 화면표시
- Money Management 선택기능추가(0,1,2,3)
- M5 차트 제한 기능추가(Period Protection)
- 주문시 사운드 사용기능 추가
- 화면표시기능 수정
- Sigma Additional 기능 추가
- 개별 Money Management Filter 추가
- 수익계산에 수수료, Swap 포함
- 승률계산 함수반영 화면표시
- Logic Parameter 수정(전략별 MA Period 차등화 변수추가, 중복주문 감소목적)
- 현재가와 종가 이격측정(Pip단위)을 위한 LastMargin 변수추가
- 현재가 기준을 매수, 매도별 Ask, Bid 수정
- Logic Code 정리
- Account Number Protection
- TotalMaxTrades(총 Open가능 거래수) 추가
- Correlation Function 추가(USDCHF Entry)

*/

//******************************************************************************
//| 상수설정                                                                   |
//******************************************************************************

#define EA_NAME "UsdChf_Guri_V0.1"
#define Copyrights "Y.S.Park"
#define Create_Date "2012-11-10"

//******************************************************************************
//| Import Library                                                             |
//******************************************************************************
#import "stdlib.ex4"
   string ErrorDescription(int a0);

//******************************************************************************
//| 공통 변수 설정                                                             |
//******************************************************************************

extern string order_set_string = "Order&Close Settings";
int AccNumber01 = 706465;                         // Valid Account Number
int AccNumber02 = 172920;                         // Valid Account Number
int AccNumber03 = 168186;                         // Valid Account Number

// 주문관련 변수설정 
extern bool ECN = TRUE;                           // ECN Broker 주문처리 가능여부
extern double FixLot=0.1 ;                        // 진입 랏사이즈 설정
extern double slippage = 3.0;                     // 슬리피지 허용 변수
string Commentary = EA_NAME;                      // Entry 주문시 비고 
string BaseSymbol = "EURUSD";                     // 기준 통화 
string EntrySymbol = "USDCHF";                    // Entry 통화 

// 일괄청산관련 설정
extern double StopOutBalance = 50;                // 모든 거래 종료 잔고 설정
extern bool CloseAllFilter = TRUE;                // Close All 가능여부
extern int All_SL = 60;                           // 1개 이상시 CloseAll StopLoss
extern int All_TP = 100;                          // 1개 이상시 CloseAll TakeProfit

// Sound 관련
extern bool SoundEnabled1 = TRUE;                  // Buy 주문시 소리 사용여부
extern bool SoundEnabled2 = TRUE;                  // Sell 주문시 소리 사용여부
extern bool SoundEnabled3 = TRUE;                  // Close Buy시 소리 사용여부
extern bool SoundEnabled4 = TRUE;                  // Close Sell시 소리 사용여부

string sound1 = "st1order.wav";                    // Buy 주문시 사용 소리파일 
string sound2 = "st2order.wav";                    // Sell 주문시 사용 소리파일
string sound3 = "st3order.wav";                    // Close Buy 시 사용 소리파일
string sound4 = "st4order.wav";                    // Close Sell시 사용 소리파일

//******************************************************************************
//| 전략1 일반 변수설정                                                        |
//******************************************************************************

extern string Strategy1_set = "Strategy1_Order&Close Settings";
extern bool Strategy1 = TRUE;                       // 전략1 사용여부
extern int XSL1 = 100;                              // StopLoss
extern int XTP1 = 100;                              // TakeProfit
extern bool AddFilter1 = TRUE;                      // Additional Entry 가능여부
extern double AddLotMultiplier1 = 2;                // Additional Lot Multiplier
extern int AddLossPip1 = 5;                         // Additional Entry Loss Pips
string Com1 = "Sto1_Init";                          // Entry 주문시 비고
string Com12 = "Sto1_Add";                          // Entry 주문시 비고 
int magic1, magic12;
extern bool CloseFilter1 = TRUE;                    // 청산시 지표사용

// Trailing Stop/Break Even 관련 설정
extern double  TrailingStop1 = 20.0;                // Trailing Stop 설정시 > 0
extern double  BreakEven1 = 12.0;                   // Break Even 설정시 > 0
extern double  BreakPoint1 = 3.0;                   // Break Even 설정시 손절치(본전 + 손절치)

// Money Management 설정
extern string MM_set_string1 = "MM = 0:FixLot,1:Percent,2:Conservative,3:Aggresive";
extern int DynamicMM1 = 0;                          // Money Management 설정 0:FixLot,1:Percent,2:Conservative,3:Aggresive 
extern double RiskPercent1 = 5.0;                   // MM = 1일때 0보다 큰 숫자 설정


//******************************************************************************
//| 전략2 일반 변수설정                                                        |
//******************************************************************************

extern string Strategy2_set = "Strategy2_Order&Close Settings";
extern bool Strategy2 = TRUE;                       // 전략2 사용여부
extern int XSL2 = 100;                              // StopLoss
extern int XTP2 = 100;                              // TakeProfit
extern bool AddFilter2 = TRUE;                      // Additional Entry 가능여부
extern double AddLotMultiplier2 = 2;                // Additional Lot Multiplier
extern int AddLossPip2 = 5;                         // Additional Entry Loss Pips
string Com2 = "Sto2_Init";                          // Entry 주문시 비고
string Com22 = "Sto2_Add";                          // Entry 주문시 비고 
int magic2, magic22;
extern bool CloseFilter2 = TRUE;                    // 청산시 지표사용

// Trailing Stop/Break Even 관련 설정
extern double  TrailingStop2 = 20.0;                // Trailing Stop 설정시 > 0
extern double  BreakEven2 = 12.0;                   // Break Even 설정시 > 0
extern double  BreakPoint2 = 3.0;                   // Break Even 설정시 손절치(본전 + 손절치)

// Money Management 설정
extern string MM_set_string2 = "MM = 0:FixLot,1:Percent,2:Conservative,3:Aggresive";
extern int DynamicMM2 = 0;                          // Money Management 설정 0:FixLot,1:Percent,2:Conservative,3:Aggresive 
extern double RiskPercent2 = 5.0;                   // MM = 1일때 0보다 큰 숫자 설정

//******************************************************************************
//| 전략3 일반 변수설정                                                        |
//******************************************************************************

extern string Strategy3_set = "Strategy3_Order&Close Settings";
extern bool Strategy3 = TRUE;                       // 전략3 사용여부
extern int XSL3 = 100;                              // StopLoss
extern int XTP3 = 100;                              // TakeProfit
extern bool AddFilter3 = TRUE;                      // Additional Entry 가능여부
extern double AddLotMultiplier3 = 2;                // Additional Lot Multiplier
extern int AddLossPip3 = 5;                         // Additional Entry Loss Pips
string Com3 = "CCI3_Init";                          // Entry 주문시 비고
string Com32 = "CCI3_Add";                          // Entry 주문시 비고 
int magic3, magic32;
extern bool CloseFilter3 = TRUE;                    // 청산시 지표사용

// Trailing Stop/Break Even 관련 설정
extern double  TrailingStop3 = 20.0;                // Trailing Stop 설정시 > 0
extern double  BreakEven3 = 12.0;                   // Break Even 설정시 > 0
extern double  BreakPoint3 = 3.0;                   // Break Even 설정시 손절치(본전 + 손절치)

// Money Management 설정
extern string MM_set_string3 = "MM = 0:FixLot,1:Percent,2:Conservative,3:Aggresive";
extern int DynamicMM3 = 0;                          // Money Management 설정 0:FixLot,1:Percent,2:Conservative,3:Aggresive 
extern double RiskPercent3 = 5.0;                   // MM = 1일때 0보다 큰 숫자 설정

//******************************************************************************
//| 전략4 일반 변수설정                                                        |
//******************************************************************************

extern string Strategy4_set = "Strategy4_Order&Close Settings";
extern bool Strategy4 = TRUE;                       // 전략4 사용여부
extern int XSL4 = 100;                              // StopLoss
extern int XTP4 = 100;                              // TakeProfit
extern bool AddFilter4 = TRUE;                      // Additional Entry 가능여부
extern double AddLotMultiplier4 = 2;                // Additional Lot Multiplier
extern int AddLossPip4 = 5;                         // Additional Entry Loss Pips
string Com4 = "WPR4_Init";                          // Entry 주문시 비고
string Com42 = "WPR4_Add";                          // Entry 주문시 비고 
int magic4, magic42;
extern bool CloseFilter4 = TRUE;                    // 청산시 지표사용

// Trailing Stop/Break Even 관련 설정
extern double  TrailingStop4 = 20.0;                // Trailing Stop 설정시 > 0
extern double  BreakEven4 = 12.0;                   // Break Even 설정시 > 0
extern double  BreakPoint4 = 3.0;                   // Break Even 설정시 손절치(본전 + 손절치)

// Money Management 설정
extern string MM_set_string4 = "MM = 0:FixLot,1:Percent,2:Conservative,3:Aggresive";
extern int DynamicMM4 = 0;                          // Money Management 설정 0:FixLot,1:Percent,2:Conservative,3:Aggresive 
extern double RiskPercent4 = 5.0;                   // MM = 1일때 0보다 큰 숫자 설정

//******************************************************************************
//| 제한조건 관련 설정(Max Spread, Max Trades, Day/Time Filter 등)             |
//******************************************************************************

extern string limit_set_string = "Limitation Settings";
extern int MaxSpreads = 4;                        // 최대 허용 Spread(Pip)
extern bool OrderTotalControl = FALSE;            // Ture : 총 허용거래수, False : 각 Type별 허용 거래수
extern int TotalMaxTrades = 5;                    // 총 최대 허용 거래수
extern int MaxTrades = 1;                         // 전략당 최대 허용 거래수
extern int MinBars = 100;                         // 최소 다운로드 Bar의 수
extern int MoneyEnable = 100;                     // 최소 거래 가능 금액 설정

extern bool DateFilter = TRUE;                    // Day Filter설정, False시 Day/Time Filter off 
extern bool TimeFilter = TRUE;                    // Time Filter 설정 
extern bool MON = TRUE;                           // 월요일 거래허용 여부
extern bool TUE = TRUE;                           // 화요일 거래허용 여부
extern bool WED = TRUE;                           // 수요일 거래허용 여부
extern bool THU = TRUE;                           // 목요일 거래허용 여부
extern bool FRI = TRUE;                           // 금요일 거래허용 여부

extern string timesetting_str = "finish time을 23:59로 하고자 하는 경우 finish time을 25로 설정"; 
extern int mon_start_time = 1;                    // 월요일 거래시작시간
extern int mon_finish_time = 25;                  // 월요일 거래종료시간 
extern int tue_start_time = 0;                    // 화요일 거래시작시간
extern int tue_finish_time = 25;                  // 화요일 거래종료시간 
extern int wed_start_time = 0;                    // 수요일 거래시작시간  
extern int wed_finish_time = 25;                  // 수요일 거래종료시간  
extern int thu_start_time = 0;                    // 목요일 거래시작시간
extern int thu_finish_time = 25;                  // 목요일 거래종료시간 
extern int fri_start_time = 0;                    // 금요일 거래시작시간
extern int fri_finish_time = 18;                  // 금요일 거래종료시간 

//******************************************************************************
//| 전략 Entry Logic 관련 변수 설정                                            |
//******************************************************************************

extern string strat1_entry_string = "Strategy1_Entry Settings";
// 공통변수
extern int TF01 = 15;
extern int Shift01 = 1;
extern int ATR_Period01 = 40;
extern int ATR_Value = 6;
extern int LastMargin = 5;
extern int Sto_KPeriod01 = 11;
extern int Sto_DPeriod01 = 1;
extern int Sto_Slowing01 = 1;
extern int StoCloseBuyTarget = 10;
extern int StoCloseSellTarget = 10;
extern int NowTF01 = 1;
extern int CorPeriod = 3;
extern double TargetCor = 0.9;

// 전략1 Parameter
extern int MA1_Period01 = 59;
extern int MA1_BuyGapValue = 18; 
extern int MA1_SellGapValue = 18; 
extern int S1StoTaget = 1;

// Close Parameter
extern int S1MinProfit = 15;
extern int S1PriceTarget = 10;

// 전략2 Parameter
extern string strat2_entry_string = "Strategy2_Entry Settings";
extern int MA2_Period01 = 55;
extern int MA2_BuyGapValue = 41; 
extern int MA2_SellGapValue = 43;
extern int S2StoTaget = 5;

// Close Parameter
extern int S2MinProfit = 5;
extern int S2PriceTarget = 15;

// 전략3 Parameter
extern string strat3_entry_string = "Strategy3_Entry Settings";
extern int MA3_Period01 = 55;
extern int MA3_BuyGapValue = 36; 
extern int MA3_SellGapValue = 42; 
extern int CCI_Period01 = 18;
extern int CCI_Limit01 = 150;

// Close Parameter
extern int S3MinProfit = 5;
extern int S3PriceTarget = 15;

// 전략4 Parameter
extern string strat4_entry_string = "Strategy4_Entry Settings";
extern int MA4_Period01 = 55;
extern int MA4_BuyGapValue = 41; 
extern int MA4_SellGapValue = 43; 
extern int WPR_Period01 = 10;
extern int WPR_Period02 = 12;
extern int ExtraWPR1 = 3;
extern int ExtraWPR2 = 5;

// Close Parameter
extern int S4MinProfit = 5;
extern int S4PriceTarget = 15;

//******************************************************************************
//| 기타 내생 변수 설정                                                        |
//******************************************************************************

int mypoint, mypoints;                           // 4 digit, 5digit broker에 대한 point 설정변수
string NowSym, StartDay;                         // EA 시작일 및 심볼 조정변수
int error_code;                                  // 에러코드 

datetime  S1Time1,S1Time2;                       // Strategy1 NewBar 시간변수
datetime  S12Time1,S12Time2;                     // Strategy1-2 NewBar 시간변수
datetime  S2Time1,S2Time2;                       // Strategy2 NewBar 시간변수
datetime  S22Time1,S22Time2;                     // Strategy2-2 NewBar 시간변수
datetime  S3Time1,S3Time2;                       // Strategy3 NewBar 시간변수
datetime  S32Time1,S32Time2;                     // Strategy3-2 NewBar 시간변수
datetime  S4Time1,S4Time2;                       // Strategy4 NewBar 시간변수
datetime  S42Time1,S42Time2;                     // Strategy4-2 NewBar 시간변수

// MarketInfo 정보를 받는 변수
string broker,servername,mytime,ScreenStr;
double equity,reqmargin,stopout,minlot,maxlot,lotstep;
double accfree,sympoint,ask00,bid00,spread,tickvalue,ticksize, sympoints;
int leverage,mydigit,stoplevel,freeze;


//******************************************************************************
//| 초기화                                                                     |
//******************************************************************************

int init() {  // 초기화 시작

// EA Validation Check
   if(CheckValid()==FALSE) {
     return(0);
   } 

// Period Protection
   if(Period() != PERIOD_M5) {
     Alert("5분봉 차트에 붙이셔야 합니다.");
     return(0);
   }  

// Symbol Protection
   if (StringSubstr(Symbol(), 0, 6) != "EURUSD" && StringSubstr(Symbol(), 0, 6) != "USDCHF") {
      Alert("EURUSD, USDCHF 말고는 취급안해!");
      return (0);
   }

// 거래 가능여부 확인
   if(IsTradeAllowed()) {
    Print("거래 가능합니다!");
    Print("1분봉 "+iBars(Symbol(), 1)+" 개, 5분봉 "+iBars(Symbol(), 5)+" 개, 15분봉 "+iBars(Symbol(), 15)+" 개 수령");
   }
   
// Money Management 정확한 설정확인   
   if((DynamicMM1 == 1 && RiskPercent1 == 0) || (DynamicMM2 == 1 && RiskPercent2 == 0) || (DynamicMM3 == 1 && RiskPercent3 == 0) || (DynamicMM4 == 1 && RiskPercent4 == 0) ) {
    Alert("RiskPercent값을 0 이상으로 설정하세요.");
    return(0);
   }
   
   if( DynamicMM1 > 3 || DynamicMM2 > 3 || DynamicMM3 > 3 || DynamicMM4 > 3 ) {
    Alert("DynamicMM값을 3 이하값으로 설정하세요.");
    return(0);
   }

// 전략 사용가능 체크
   if(!Strategy1 && !Strategy2 && !Strategy3 && !Strategy4) {
     Alert("적어도 하나의 전략은 사용가능해야 합니다.");
     return(0);
   }  

// 데이타 다운로드 미비에 의한 오류계산 방지 로직
   if(!DataFilter()) {
     Print ("아! Bar가 아직 모자라!ㅠㅠ..");
     return(0);
   }

// EA 시작일 설정
   StartDay = TimeToStr(TimeCurrent(),TIME_DATE); 

// 통화별 매직넘버 가져오기(최초 작업시 매직넘버 수정요망)
   getmagic();
   magic2 = magic1+10000;
   magic3 = magic2+10000;
   magic4 = magic3+10000;   
   magic12 = magic1+5000;    
   magic22 = magic2+5000;  
   magic32 = magic3+5000;   
   magic42 = magic4+5000;

// 5 digit broker adjustment

   if(MarketInfo(EntrySymbol, MODE_DIGITS)==3 || MarketInfo(EntrySymbol, MODE_DIGITS)==5) {
       mypoint = 10;
   }       
   else
   { 
       mypoint = 1;
   }    

   if(MarketInfo(BaseSymbol, MODE_DIGITS)==3 || MarketInfo(BaseSymbol, MODE_DIGITS)==5) {
       mypoints = 10;
   }       
   else
   { 
       mypoints = 1;
   }    
}    // 초기화 종료

//******************************************************************************
//| 종료시 설정                                                                |
//******************************************************************************

int deinit()  {
   return(0);
  }


//******************************************************************************
//| EA Start                                                                   |
//******************************************************************************

int start() {   // EA 시작

//******************************************************************************
// Error 검출후 메세지 출력
// EA 거래를 막아놓은 경우
  if(!IsTesting()) {
   if(!IsDllsAllowed() || !IsExpertEnabled()) {
     Print("DLL 사용할 수 있게 옵션에서 풀어주세요. 혹은 EA아이콘 확인요망!");
     return(0);
     }
  }  
  
//******************************************************************************
// MarketInfo 정보를 받는 변수 설정

    broker     = AccountCompany();
    servername = AccountServer();
    mytime     = TimeToStr(TimeCurrent(),TIME_SECONDS);
    equity     = AccountEquity();
    leverage   = AccountLeverage();   
    reqmargin  = MarketInfo(Symbol(), MODE_MARGINREQUIRED);
    accfree    = NormalizeDouble(AccountFreeMargin(),2);
    ask00      = MarketInfo(Symbol(),MODE_ASK);
    bid00      = MarketInfo(Symbol(),MODE_BID);

    stoplevel  = MarketInfo(Symbol(), MODE_STOPLEVEL);
    freeze     = MarketInfo(Symbol(), MODE_FREEZELEVEL);    
    stopout    = AccountStopoutLevel();
    mydigit    = MarketInfo(Symbol(), MODE_DIGITS);
    sympoints  = MarketInfo(BaseSymbol,MODE_POINT);
    sympoint   = MarketInfo(EntrySymbol,MODE_POINT);    
    minlot     = MarketInfo(Symbol(), MODE_MINLOT);
    maxlot     = MarketInfo(Symbol(), MODE_MAXLOT);
    lotstep    = MarketInfo(Symbol(), MODE_LOTSTEP);
    spread     = NormalizeDouble(ask00-bid00,mydigit); 
    tickvalue  = MarketInfo(Symbol(), MODE_TICKVALUE);
    ticksize   = MarketInfo(Symbol(), MODE_TICKSIZE);
  
//******************************************************************************
// StopOut Balance도달시 강제청산함수 가져오기

   StopOutClose();

//******************************************************************************
// Trailing Stop / Break Even 함수 가져오기
    
   if(TrailingStop1>0) MoveTrailingStop(magic1,TrailingStop1);
   if(BreakEven1>0) MoveBreakEven(magic1,BreakEven1,BreakPoint1);

   if(TrailingStop1>0) MoveTrailingStop(magic12,TrailingStop1);
   if(BreakEven1>0) MoveBreakEven(magic12,BreakEven1,BreakPoint1);

   if(TrailingStop2>0) MoveTrailingStop(magic2,TrailingStop2);
   if(BreakEven2>0) MoveBreakEven(magic2,BreakEven2,BreakPoint2);

   if(TrailingStop2>0) MoveTrailingStop(magic22,TrailingStop2);
   if(BreakEven2>0) MoveBreakEven(magic22,BreakEven2,BreakPoint2);

   if(TrailingStop3>0) MoveTrailingStop(magic3,TrailingStop3);
   if(BreakEven3>0) MoveBreakEven(magic3,BreakEven3,BreakPoint3);

   if(TrailingStop3>0) MoveTrailingStop(magic32,TrailingStop3);
   if(BreakEven3>0) MoveBreakEven(magic32,BreakEven3,BreakPoint3);

   if(TrailingStop4>0) MoveTrailingStop(magic4,TrailingStop4);
   if(BreakEven4>0) MoveBreakEven(magic4,BreakEven4,BreakPoint4);

   if(TrailingStop4>0) MoveTrailingStop(magic42,TrailingStop4);
   if(BreakEven4>0) MoveBreakEven(magic42,BreakEven4,BreakPoint4);         
  
//******************************************************************************
//| Date/Time Filter                                                           |
//******************************************************************************  
// Day/Time Filter충족여부 검토

   bool DateEnabled = FALSE;
 
   if (DayFilter()) DateEnabled = TRUE;
   else DateEnabled = FALSE;
   
//******************************************************************************
// Spread 조건 충족여부 검토 

   bool SpreadEnabled = FALSE;
   
   if (TradeEnable()==FALSE) {
     Print ("아! Spread가 너무 쎄!ㅠㅠ..");
     SpreadEnabled = FALSE;
    } 
   else SpreadEnabled = TRUE;

//******************************************************************************
// 잔고가 일정액 이하인 경우 EA 진입금지
  bool EnoughMoney = TRUE;
    
  if(accfree < MoneyEnable) {
    Print("돈이 없어. 현잔고 = ", accfree);
    EnoughMoney = FALSE;
   }   
   else EnoughMoney = TRUE;

//******************************************************************************
// 총 Open Position이 TotalMaxTrades 이상인 경우 EA 진입금지
  bool EntryTotalOver = FALSE;
  int EntryTotal = TotalOrders(magic1)+TotalOrders(magic2)+TotalOrders(magic3)+TotalOrders(magic4)+TotalOrders(magic12)+TotalOrders(magic22)+TotalOrders(magic32)+TotalOrders(magic42);
    
  if(EntryTotal < TotalMaxTrades) {
    EntryTotalOver = TRUE;
   }   
   else EntryTotalOver = FALSE;

//******************************************************************************
// Spread조건 및 Day/Time Filter충족여부 검토 
   
   bool EntryEnabled = FALSE;   
   if (DateEnabled && SpreadEnabled && EnoughMoney && EntryTotalOver) EntryEnabled = TRUE;
   else EntryEnabled = FALSE;


//******************************************************************************
//| Order 주문처리 Logic                                                       |
//******************************************************************************
//******************************************************************************
// 전략1 주문 처리

  bool Entry_1 = FALSE;

  if(EntryEnabled && Strategy1) Entry_1 = TRUE;
  else Entry_1 = FALSE; 
  
  bool S1NewBarBuy = FALSE;
  bool S1NewBarSell = FALSE;

  if(S1Time1 < Time[0]) {  // 1
      S1Time1 = Time[0];
      S1NewBarBuy = TRUE;
   }  // 1
   else S1NewBarBuy = FALSE;

  if(S1Time2 < Time[0]) {  // 1
      S1Time2 = Time[0];
      S1NewBarSell = TRUE;
   }  // 1
   else S1NewBarSell = FALSE;

//******************************************************************************
// Strategy 1 Order Processing

  int ticketbuy1, ticketsell1;  
  double orderlot1 = NormalizeDouble(MoneyManagement(DynamicMM1,RiskPercent1),2);

// Buy Order

  if(OrderTotalControl) {
    if(Entry_1 && TotalOrders(magic1) < MaxTrades && S1NewBarBuy) {
     if(ST1Sell()) {
     ticketbuy1 = OpenOrder(Symbol(),OP_BUY,orderlot1,slippage,XSL1,XTP1,Com1,magic1);
     }
    } 
  }   
  else
  if(!OrderTotalControl) {
    if(Entry_1 && TotalBuyOrders(magic1) < MaxTrades && S1NewBarBuy) {
     if(ST1Sell()) {
     ticketbuy1 = OpenOrder(Symbol(),OP_BUY,orderlot1,slippage,XSL1,XTP1,Com1,magic1);
     }
    } 
  }

// Sell Order

  if(OrderTotalControl) {
    if(Entry_1 && TotalOrders(magic1) < MaxTrades && S1NewBarSell) {
     if(ST1Buy()) {
     ticketsell1 = OpenOrder(Symbol(),OP_SELL,orderlot1,slippage,XSL1,XTP1,Com1,magic1);
     }
    } 
  }   
  else
  if(!OrderTotalControl) {
    if(Entry_1 && TotalSellOrders(magic1) < MaxTrades && S1NewBarSell) {
     if(ST1Buy()) {
     ticketsell1 = OpenOrder(Symbol(),OP_SELL,orderlot1,slippage,XSL1,XTP1,Com1,magic1);
     }
    } 
  } 
  
//******************************************************************************
// 전략2 주문 처리

  bool Entry_2 = FALSE;

  if(EntryEnabled && Strategy2) Entry_2 = TRUE;
  else Entry_2 = FALSE; 
  
  bool S2NewBarBuy = FALSE;
  bool S2NewBarSell = FALSE;

  if(S2Time1 < Time[0]) {  // 1
      S2Time1 = Time[0];
      S2NewBarBuy = TRUE;
   }  // 1
   else S2NewBarBuy = FALSE;

  if(S2Time2 < Time[0]) {  // 1
      S2Time2 = Time[0];
      S2NewBarSell = TRUE;
   }  // 1
   else S2NewBarSell = FALSE;

//******************************************************************************
// Strategy 2 Order Processing

  int ticketbuy2, ticketsell2;  
  double orderlot2 = NormalizeDouble(MoneyManagement(DynamicMM2,RiskPercent2),2);

// Buy Order

  if(OrderTotalControl) {
    if(Entry_2 && TotalOrders(magic2) < MaxTrades && S2NewBarBuy) {
     if(ST2Sell()) {
     ticketbuy2 = OpenOrder(Symbol(),OP_BUY,orderlot2,slippage,XSL2,XTP2,Com2,magic2);
     }
    } 
  }   
  else
  if(!OrderTotalControl) {
    if(Entry_2 && TotalBuyOrders(magic2) < MaxTrades && S2NewBarBuy) {
     if(ST2Sell()) {
     ticketbuy2 = OpenOrder(Symbol(),OP_BUY,orderlot2,slippage,XSL2,XTP2,Com2,magic2);
     }
    } 
  }

// Sell Order

  if(OrderTotalControl) {
    if(Entry_2 && TotalOrders(magic2) < MaxTrades && S2NewBarSell) {
     if(ST2Buy()) {
     ticketsell2 = OpenOrder(Symbol(),OP_SELL,orderlot2,slippage,XSL2,XTP2,Com2,magic2);
     }
    } 
  }   
  else
  if(!OrderTotalControl) {
    if(Entry_2 && TotalSellOrders(magic2) < MaxTrades && S2NewBarSell) {
     if(ST2Buy()) {
     ticketsell2 = OpenOrder(Symbol(),OP_SELL,orderlot2,slippage,XSL2,XTP2,Com2,magic2);
     }
    } 
  }   


//******************************************************************************
// 전략3 주문 처리

  bool Entry_3 = FALSE;

  if(EntryEnabled && Strategy3) Entry_3 = TRUE;
  else Entry_3 = FALSE; 
  
  bool S3NewBarBuy = FALSE;
  bool S3NewBarSell = FALSE;

  if(S3Time1 < Time[0]) {  // 1
      S3Time1 = Time[0];
      S3NewBarBuy = TRUE;
   }  // 1
   else S3NewBarBuy = FALSE;

  if(S3Time2 < Time[0]) {  // 1
      S3Time2 = Time[0];
      S3NewBarSell = TRUE;
   }  // 1
   else S3NewBarSell = FALSE;

//******************************************************************************
// Strategy 3 Order Processing

  int ticketbuy3, ticketsell3;  
  double orderlot3 = NormalizeDouble(MoneyManagement(DynamicMM3,RiskPercent3),2);

// Buy Order

  if(OrderTotalControl) {
    if(Entry_3 && TotalOrders(magic3) < MaxTrades && S3NewBarBuy) {
     if(ST3Sell()) {
     ticketbuy3 = OpenOrder(Symbol(),OP_BUY,orderlot3,slippage,XSL3,XTP3,Com3,magic3);
     }
    } 
  }   
  else
  if(!OrderTotalControl) {
    if(Entry_3 && TotalBuyOrders(magic3) < MaxTrades && S3NewBarBuy) {
     if(ST3Sell()) {
     ticketbuy3 = OpenOrder(Symbol(),OP_BUY,orderlot3,slippage,XSL3,XTP3,Com3,magic3);
     }
    } 
  }

// Sell Order

  if(OrderTotalControl) {
    if(Entry_3 && TotalOrders(magic3) < MaxTrades && S3NewBarSell) {
     if(ST3Buy()) {
     ticketsell3 = OpenOrder(Symbol(),OP_SELL,orderlot3,slippage,XSL3,XTP3,Com3,magic3);
     }
    } 
  }   
  else
  if(!OrderTotalControl) {
    if(Entry_3 && TotalSellOrders(magic3) < MaxTrades && S3NewBarSell) {
     if(ST3Buy()) {
     ticketsell3 = OpenOrder(Symbol(),OP_SELL,orderlot3,slippage,XSL3,XTP3,Com3,magic3);
     }
    } 
  } 
  
//******************************************************************************
// 전략4 주문 처리

  bool Entry_4 = FALSE;

  if(EntryEnabled && Strategy4) Entry_4 = TRUE;
  else Entry_4 = FALSE; 
  
  bool S4NewBarBuy = FALSE;
  bool S4NewBarSell = FALSE;

  if(S4Time1 < Time[0]) {  // 1
      S4Time1 = Time[0];
      S4NewBarBuy = TRUE;
   }  // 1
   else S4NewBarBuy = FALSE;

  if(S4Time2 < Time[0]) {  // 1
      S4Time2 = Time[0];
      S4NewBarSell = TRUE;
   }  // 1
   else S4NewBarSell = FALSE;

//******************************************************************************
// Strategy 4 Order Processing

  int ticketbuy4, ticketsell4;  
  double orderlot4 = NormalizeDouble(MoneyManagement(DynamicMM4,RiskPercent4),2);

// Buy Order

  if(OrderTotalControl) {
    if(Entry_4 && TotalOrders(magic4) < MaxTrades && S4NewBarBuy) {
     if(ST4Sell()) {
     ticketbuy4 = OpenOrder(Symbol(),OP_BUY,orderlot4,slippage,XSL4,XTP4,Com4,magic4);
     }
    } 
  }   
  else
  if(!OrderTotalControl) {
    if(Entry_4 && TotalBuyOrders(magic4) < MaxTrades && S4NewBarBuy) {
     if(ST4Sell()) {
     ticketbuy4 = OpenOrder(Symbol(),OP_BUY,orderlot4,slippage,XSL4,XTP4,Com4,magic4);
     }
    } 
  }

// Sell Order

  if(OrderTotalControl) {
    if(Entry_4 && TotalOrders(magic4) < MaxTrades && S4NewBarSell) {
     if(ST4Buy()) {
     ticketsell4 = OpenOrder(Symbol(),OP_SELL,orderlot4,slippage,XSL4,XTP4,Com4,magic4);
     }
    } 
  }   
  else
  if(!OrderTotalControl) {
    if(Entry_4 && TotalSellOrders(magic4) < MaxTrades && S4NewBarSell) {
     if(ST4Buy()) {
     ticketsell4 = OpenOrder(Symbol(),OP_SELL,orderlot4,slippage,XSL4,XTP4,Com4,magic4);
     }
    } 
  }  


//******************************************************************************
//| Strategy 1~4-2 Buy/Sell Condition Function(Additional Order)               |
//******************************************************************************
//******************************************************************************
// 1-2 Additional Buy/Sell 

   bool Buy12Con = FALSE;  
   bool Sell12Con = FALSE;     

   if ( TotalBuyOrders(magic1)>0 && ST1Sell() && ask00 < FindLastBuyPrice(magic1) - AddLossPip1 * mypoint * sympoint ) Buy12Con = TRUE;
   else Buy12Con = FALSE;
    
   if ( TotalSellOrders(magic1)>0 && ST1Buy() && bid00 > FindLastSellPrice(magic1) + AddLossPip1 * mypoint * sympoint ) Sell12Con = TRUE;
   else Sell12Con = FALSE;    

//******************************************************************************
// Strategy 1-2 New Bar

  bool S12NewBarBuy = FALSE;
  bool S12NewBarSell = FALSE;

  if(S12Time1 < Time[0]) {  // 1
      S12Time1 = Time[0];
      S12NewBarBuy = TRUE;
   }  // 1
   else S12NewBarBuy = FALSE;

  if(S12Time2 < Time[0]) {  // 1
      S12Time2 = Time[0];
      S12NewBarSell = TRUE;
   }  // 1
   else S12NewBarSell = FALSE;

//******************************************************************************
// Strategy 1-2 Order Processing

  double orderlot12 = NormalizeDouble(MoneyManagement(DynamicMM1,RiskPercent1)*AddLotMultiplier1,2);
  int ticketbuy12, ticketsell12;  
  
// Buy Order

  if(OrderTotalControl) {
    if(Entry_1 && AddFilter1 && TotalOrders(magic12) < MaxTrades && S12NewBarBuy) {
     if(Buy12Con) {
     ticketbuy12 = OpenOrder(Symbol(),OP_BUY,orderlot12,slippage,XSL1,XTP1,Com12,magic12);
     }
    } 
  }   
  else
  if(!OrderTotalControl) {
    if(Entry_1 && AddFilter1 && TotalBuyOrders(magic12) < MaxTrades && S12NewBarBuy) {
     if(Buy12Con) {
     ticketbuy12 = OpenOrder(Symbol(),OP_BUY,orderlot12,slippage,XSL1,XTP1,Com12,magic12);
     }
    } 
  }

// Sell Order

  if(OrderTotalControl) {
    if(Entry_1 && AddFilter1 && TotalOrders(magic12) < MaxTrades && S12NewBarSell) {
     if(Sell12Con) {
     ticketsell12 = OpenOrder(Symbol(),OP_SELL,orderlot12,slippage,XSL1,XTP1,Com12,magic12);
     }
    } 
  }   
  else
  if(!OrderTotalControl) {
    if(Entry_1 && AddFilter1 && TotalSellOrders(magic12) < MaxTrades && S12NewBarSell) {
     if(Sell12Con) {
     ticketsell12 = OpenOrder(Symbol(),OP_SELL,orderlot12,slippage,XSL1,XTP1,Com12,magic12);
     }
    } 
  } 

//******************************************************************************
// 2-2 Additional Buy/Sell 

   bool Buy22Con = FALSE;  
   bool Sell22Con = FALSE;     

   if ( TotalBuyOrders(magic2)>0 && ST2Sell() && ask00 < FindLastBuyPrice(magic2) - AddLossPip2 * mypoint * sympoint ) Buy22Con = TRUE;
   else Buy22Con = FALSE;
    
   if ( TotalSellOrders(magic2)>0 && ST2Buy() && bid00 > FindLastSellPrice(magic2) + AddLossPip2 * mypoint * sympoint ) Sell22Con = TRUE;
   else Sell22Con = FALSE;    

//******************************************************************************
// Strategy 2-2 New Bar

  bool S22NewBarBuy = FALSE;
  bool S22NewBarSell = FALSE;

  if(S22Time1 < Time[0]) {  // 1
      S22Time1 = Time[0];
      S22NewBarBuy = TRUE;
   }  // 1
   else S22NewBarBuy = FALSE;

  if(S22Time2 < Time[0]) {  // 1
      S22Time2 = Time[0];
      S22NewBarSell = TRUE;
   }  // 1
   else S22NewBarSell = FALSE;

//******************************************************************************
// Strategy 2-2 Order Processing

  double orderlot22 = NormalizeDouble(MoneyManagement(DynamicMM2,RiskPercent2)*AddLotMultiplier2,2);
  int ticketbuy22, ticketsell22;  
  
// Buy Order

  if(OrderTotalControl) {
    if(Entry_2 && AddFilter2 && TotalOrders(magic22) < MaxTrades && S22NewBarBuy) {
     if(Buy22Con) {
     ticketbuy22 = OpenOrder(Symbol(),OP_BUY,orderlot22,slippage,XSL2,XTP2,Com22,magic22);
     }
    } 
  }   
  else
  if(!OrderTotalControl) {
    if(Entry_2 && AddFilter2 && TotalBuyOrders(magic22) < MaxTrades && S22NewBarBuy) {
     if(Buy22Con) {
     ticketbuy22 = OpenOrder(Symbol(),OP_BUY,orderlot22,slippage,XSL2,XTP2,Com22,magic22);
     }
    } 
  }

// Sell Order

  if(OrderTotalControl) {
    if(Entry_2 && AddFilter2 && TotalOrders(magic22) < MaxTrades && S22NewBarSell) {
     if(Sell22Con) {
     ticketsell22 = OpenOrder(Symbol(),OP_SELL,orderlot22,slippage,XSL2,XTP2,Com22,magic22);
     }
    } 
  }   
  else
  if(!OrderTotalControl) {
    if(Entry_2 && AddFilter2 && TotalSellOrders(magic22) < MaxTrades && S22NewBarSell) {
     if(Sell22Con) {
     ticketsell22 = OpenOrder(Symbol(),OP_SELL,orderlot22,slippage,XSL2,XTP2,Com22,magic22);
     }
    } 
  } 

//******************************************************************************
// 3-2 Additional Buy/Sell 

   bool Buy32Con = FALSE;  
   bool Sell32Con = FALSE;     

   if ( TotalBuyOrders(magic3)>0 && ST3Sell() && ask00 < FindLastBuyPrice(magic3) - AddLossPip3 * mypoint * sympoint ) Buy32Con = TRUE;
   else Buy32Con = FALSE;
    
   if ( TotalSellOrders(magic3)>0 && ST3Buy() && bid00 > FindLastSellPrice(magic3) + AddLossPip3 * mypoint * sympoint ) Sell32Con = TRUE;
   else Sell32Con = FALSE;    

//******************************************************************************
// Strategy 3-2 New Bar

  bool S32NewBarBuy = FALSE;
  bool S32NewBarSell = FALSE;

  if(S32Time1 < Time[0]) {  // 1
      S32Time1 = Time[0];
      S32NewBarBuy = TRUE;
   }  // 1
   else S32NewBarBuy = FALSE;

  if(S32Time2 < Time[0]) {  // 1
      S32Time2 = Time[0];
      S32NewBarSell = TRUE;
   }  // 1
   else S32NewBarSell = FALSE;

//******************************************************************************
// Strategy 3-2 Order Processing

  double orderlot32 = NormalizeDouble(MoneyManagement(DynamicMM3,RiskPercent3)*AddLotMultiplier3,2);
  int ticketbuy32, ticketsell32;  
  
// Buy Order

  if(OrderTotalControl) {
    if(Entry_3 && AddFilter3 && TotalOrders(magic32) < MaxTrades && S32NewBarBuy) {
     if(Buy32Con) {
     ticketbuy32 = OpenOrder(Symbol(),OP_BUY,orderlot32,slippage,XSL3,XTP3,Com32,magic32);
     }
    } 
  }   
  else
  if(!OrderTotalControl) {
    if(Entry_3 && AddFilter3 && TotalBuyOrders(magic32) < MaxTrades && S32NewBarBuy) {
     if(Buy32Con) {
     ticketbuy32 = OpenOrder(Symbol(),OP_BUY,orderlot32,slippage,XSL3,XTP3,Com32,magic32);
     }
    } 
  }

// Sell Order

  if(OrderTotalControl) {
    if(Entry_3 && AddFilter3 && TotalOrders(magic32) < MaxTrades && S32NewBarSell) {
     if(Sell32Con) {
     ticketsell32 = OpenOrder(Symbol(),OP_SELL,orderlot32,slippage,XSL3,XTP3,Com32,magic32);
     }
    } 
  }   
  else
  if(!OrderTotalControl) {
    if(Entry_3 && AddFilter3 && TotalSellOrders(magic32) < MaxTrades && S32NewBarSell) {
     if(Sell32Con) {
     ticketsell32 = OpenOrder(Symbol(),OP_SELL,orderlot32,slippage,XSL3,XTP3,Com32,magic32);
     }
    } 
  } 


//******************************************************************************
// 4-2 Additional Buy/Sell 

   bool Buy42Con = FALSE;  
   bool Sell42Con = FALSE;     

   if ( TotalBuyOrders(magic4)>0 && ST4Sell() && ask00 < FindLastBuyPrice(magic4) - AddLossPip4 * mypoint * sympoint ) Buy42Con = TRUE;
   else Buy42Con = FALSE;
    
   if ( TotalSellOrders(magic4)>0 && ST4Buy() && bid00 > FindLastSellPrice(magic4) + AddLossPip4 * mypoint * sympoint ) Sell42Con = TRUE;
   else Sell42Con = FALSE;    

//******************************************************************************
// Strategy 4-2 New Bar

  bool S42NewBarBuy = FALSE;
  bool S42NewBarSell = FALSE;

  if(S42Time1 < Time[0]) {  // 1
      S42Time1 = Time[0];
      S42NewBarBuy = TRUE;
   }  // 1
   else S42NewBarBuy = FALSE;

  if(S42Time2 < Time[0]) {  // 1
      S42Time2 = Time[0];
      S42NewBarSell = TRUE;
   }  // 1
   else S42NewBarSell = FALSE;

//******************************************************************************
// Strategy 4-2 Order Processing

  double orderlot42 = NormalizeDouble(MoneyManagement(DynamicMM4,RiskPercent4)*AddLotMultiplier4,2);
  int ticketbuy42, ticketsell42;  
  
// Buy Order

  if(OrderTotalControl) {
    if(Entry_4 && AddFilter4 && TotalOrders(magic42) < MaxTrades && S42NewBarBuy) {
     if(Buy42Con) {
     ticketbuy42 = OpenOrder(Symbol(),OP_BUY,orderlot42,slippage,XSL4,XTP4,Com42,magic42);
     }
    } 
  }   
  else
  if(!OrderTotalControl) {
    if(Entry_4 && AddFilter4 && TotalBuyOrders(magic42) < MaxTrades && S42NewBarBuy) {
     if(Buy42Con) {
     ticketbuy42 = OpenOrder(Symbol(),OP_BUY,orderlot42,slippage,XSL4,XTP4,Com42,magic42);
     }
    } 
  }

// Sell Order

  if(OrderTotalControl) {
    if(Entry_4 && AddFilter4 && TotalOrders(magic42) < MaxTrades && S42NewBarSell) {
     if(Sell42Con) {
     ticketsell42 = OpenOrder(Symbol(),OP_SELL,orderlot42,slippage,XSL4,XTP4,Com42,magic42);
     }
    } 
  }   
  else
  if(!OrderTotalControl) {
    if(Entry_4 && AddFilter4 && TotalSellOrders(magic42) < MaxTrades && S42NewBarSell) {
     if(Sell42Con) {
     ticketsell42 = OpenOrder(Symbol(),OP_SELL,orderlot42,slippage,XSL4,XTP4,Com42,magic42);
     }
    } 
  } 

//******************************************************************************
//| Strategy 1~4/1-2 ~ 4-2 Close Condition Function                            |
//******************************************************************************
//******************************************************************************
// 지표사용시 Close 조건 충족시 청산(전략1 해당)

  if(CloseFilter1 && TotalBuyOrders(magic1)>0) {
    if(CloseBuyCondition(magic1, S1MinProfit, S1PriceTarget)) {
      CloseBuyOpens(magic1);  
    }
  }   
  
  if(CloseFilter1 && TotalSellOrders(magic1)>0) {
    if(CloseSellCondition(magic1, S1MinProfit, S1PriceTarget)) {
    CloseSellOpens(magic1);  
    }
  }  

//******************************************************************************
// 지표사용시 Close 조건 충족시 청산(전략1-2 해당)

  if(CloseFilter1 && TotalBuyOrders(magic12)>0) {
    if(CloseBuyCondition(magic12, S1MinProfit, S1PriceTarget)) {
      CloseBuyOpens(magic12);  
    }
  }   
  
  if(CloseFilter1 && TotalSellOrders(magic12)>0) {
    if(CloseSellCondition(magic12, S1MinProfit, S1PriceTarget)) {
    CloseSellOpens(magic12);  
    }
  } 


//******************************************************************************
// 지표사용시 Close 조건 충족시 청산(전략2 해당)

  if(CloseFilter2 && TotalBuyOrders(magic2)>0) {
    if(CloseBuyCondition(magic2, S2MinProfit, S2PriceTarget)) {
      CloseBuyOpens(magic2);  
    }
  }   
  
  if(CloseFilter2 && TotalSellOrders(magic2)>0) {
    if(CloseSellCondition(magic2, S2MinProfit, S2PriceTarget)) {
    CloseSellOpens(magic2);  
    }
  }  

//******************************************************************************
// 지표사용시 Close 조건 충족시 청산(전략2-2 해당)

  if(CloseFilter2 && TotalBuyOrders(magic22)>0) {
    if(CloseBuyCondition(magic22, S2MinProfit, S2PriceTarget)) {
      CloseBuyOpens(magic22);  
    }
  }   
  
  if(CloseFilter2 && TotalSellOrders(magic22)>0) {
    if(CloseSellCondition(magic22, S2MinProfit, S2PriceTarget)) {
    CloseSellOpens(magic22);  
    }
  } 

//******************************************************************************
// 지표사용시 Close 조건 충족시 청산(전략3 해당)

  if(CloseFilter3 && TotalBuyOrders(magic3)>0) {
    if(CloseBuyCondition(magic3, S3MinProfit, S3PriceTarget)) {
      CloseBuyOpens(magic3);  
    }
  }   
  
  if(CloseFilter3 && TotalSellOrders(magic3)>0) {
    if(CloseSellCondition(magic3, S3MinProfit, S3PriceTarget)) {
    CloseSellOpens(magic3);  
    }
  }  

//******************************************************************************
// 지표사용시 Close 조건 충족시 청산(전략3-2 해당)

  if(CloseFilter3 && TotalBuyOrders(magic32)>0) {
    if(CloseBuyCondition(magic32, S3MinProfit, S3PriceTarget)) {
      CloseBuyOpens(magic32);  
    }
  }   
  
  if(CloseFilter3 && TotalSellOrders(magic32)>0) {
    if(CloseSellCondition(magic32, S3MinProfit, S3PriceTarget)) {
    CloseSellOpens(magic32);  
    }
  } 

//******************************************************************************
// 지표사용시 Close 조건 충족시 청산(전략4 해당)

  if(CloseFilter4 && TotalBuyOrders(magic4)>0) {
    if(CloseBuyCondition(magic4, S4MinProfit, S4PriceTarget)) {
      CloseBuyOpens(magic4);  
    }
  }   
  
  if(CloseFilter4 && TotalSellOrders(magic4)>0) {
    if(CloseSellCondition(magic4, S4MinProfit, S4PriceTarget)) {
    CloseSellOpens(magic4);  
    }
  }  

//******************************************************************************
// 지표사용시 Close 조건 충족시 청산(전략4-2 해당)

  if(CloseFilter4 && TotalBuyOrders(magic42)>0) {
    if(CloseBuyCondition(magic42, S4MinProfit, S4PriceTarget)) {
      CloseBuyOpens(magic42);  
    }
  }   
  
  if(CloseFilter4 && TotalSellOrders(magic42)>0) {
    if(CloseSellCondition(magic42, S4MinProfit, S4PriceTarget)) {
    CloseSellOpens(magic42);  
    }
  } 

//******************************************************************************
//| Close All Function                                                         |
//******************************************************************************
//******************************************************************************
// 전체수익이나 손실이 설정치 이상인 경우 Close All

   double profits = Profit(magic1)+Profit(magic12)+Profit(magic2)+Profit(magic22)+Profit(magic3)+Profit(magic32)+Profit(magic4)+Profit(magic42);
   double TlLots = TotalLot(magic1)+TotalLot(magic12)+TotalLot(magic2)+TotalLot(magic22)+TotalLot(magic3)+TotalLot(magic32)+TotalLot(magic4)+TotalLot(magic42);   

// Close All TP, SL을 Lot수에 따라 조정

   double All_SLs = NormalizeDouble(All_SL*(TlLots/FixLot),0);
   double All_TPs = NormalizeDouble(All_TP*(TlLots/FixLot),0);

   if(TotalOrders(magic12)+TotalOrders(magic22)+TotalOrders(magic32)+TotalOrders(magic42) > 0 && CloseAllFilter && (profits>All_TPs || profits<-All_SLs)) {
      if(TotalBuyOrders(magic1)>0) CloseBuyOpens(magic1);
      if(TotalSellOrders(magic1)>0) CloseSellOpens(magic1);
      if(TotalBuyOrders(magic12)>0) CloseBuyOpens(magic12);
      if(TotalSellOrders(magic12)>0) CloseSellOpens(magic12); 
      if(TotalBuyOrders(magic2)>0) CloseBuyOpens(magic2);
      if(TotalSellOrders(magic2)>0) CloseSellOpens(magic2);
      if(TotalBuyOrders(magic22)>0) CloseBuyOpens(magic22);
      if(TotalSellOrders(magic22)>0) CloseSellOpens(magic22);
      if(TotalBuyOrders(magic3)>0) CloseBuyOpens(magic3);
      if(TotalSellOrders(magic3)>0) CloseSellOpens(magic3);
      if(TotalBuyOrders(magic32)>0) CloseBuyOpens(magic32);
      if(TotalSellOrders(magic32)>0) CloseSellOpens(magic32);
      if(TotalBuyOrders(magic4)>0) CloseBuyOpens(magic4);
      if(TotalSellOrders(magic4)>0) CloseSellOpens(magic4);
      if(TotalBuyOrders(magic42)>0) CloseBuyOpens(magic42);
      if(TotalSellOrders(magic42)>0) CloseSellOpens(magic42);                       
   }


//******************************************************************************
//| 화면표시 함수                                                              |
//******************************************************************************

// 화면표시 함수처리에 시간이 많이 걸려 BackTest나 최적화작업시 시간이 많이 걸리므로 이 작업시 이전에 Exit

     if(IsTesting()) return(0);
    
// 화면표시 변수 정의

     double hprofit = HistoryProfit(magic1)+HistoryProfit(magic12)+HistoryProfit(magic2)+HistoryProfit(magic22)+HistoryProfit(magic3)+HistoryProfit(magic32)+HistoryProfit(magic4)+HistoryProfit(magic42);
     int orders = TotalOrders(magic1)+TotalOrders(magic12)+TotalOrders(magic2)+TotalOrders(magic22)+TotalOrders(magic3)+TotalOrders(magic32)+TotalOrders(magic4)+TotalOrders(magic42);

     int borders = TotalBuyOrders(magic1)+TotalBuyOrders(magic12)+TotalBuyOrders(magic2)+TotalBuyOrders(magic22)+TotalBuyOrders(magic3)+TotalBuyOrders(magic32)+TotalBuyOrders(magic4)+TotalBuyOrders(magic42);
     int sorders = TotalSellOrders(magic1)+TotalSellOrders(magic12)+TotalSellOrders(magic2)+TotalSellOrders(magic22)+TotalSellOrders(magic3)+TotalSellOrders(magic32)+TotalSellOrders(magic4)+TotalSellOrders(magic42);

     int hborders = HBuyOrders(magic1)+HBuyOrders(magic12)+HBuyOrders(magic2)+HBuyOrders(magic22)+HBuyOrders(magic3)+HBuyOrders(magic32)+HBuyOrders(magic4)+HBuyOrders(magic42);
     int hsorders = HSellOrders(magic1)+HSellOrders(magic12)+HSellOrders(magic2)+HSellOrders(magic22)+HSellOrders(magic3)+HSellOrders(magic32)+HSellOrders(magic4)+HSellOrders(magic42);
     double horders = hborders+hsorders;

     double hwborders = HWBuyOrders(magic1)+HWBuyOrders(magic12)+HWBuyOrders(magic2)+HWBuyOrders(magic22)+HWBuyOrders(magic3)+HWBuyOrders(magic32)+HWBuyOrders(magic4)+HWBuyOrders(magic42);
     double hwsorders = HWSellOrders(magic1)+HWSellOrders(magic12)+HWSellOrders(magic2)+HWSellOrders(magic22)+HWSellOrders(magic3)+HWSellOrders(magic32)+HWSellOrders(magic4)+HWSellOrders(magic42);
     double hworders = hwborders+hwsorders;

     double wbprofit = BWProfit(magic1)+BWProfit(magic12)+BWProfit(magic2)+BWProfit(magic22)+BWProfit(magic3)+BWProfit(magic32)+BWProfit(magic4)+BWProfit(magic42);
     double wsprofit = SWProfit(magic1)+SWProfit(magic12)+SWProfit(magic2)+SWProfit(magic22)+SWProfit(magic3)+SWProfit(magic32)+SWProfit(magic4)+SWProfit(magic42);
     double lbprofit = BLProfit(magic1)+BLProfit(magic12)+BLProfit(magic2)+BLProfit(magic22)+BLProfit(magic3)+BLProfit(magic32)+BLProfit(magic4)+BLProfit(magic42);
     double lsprofit = SLProfit(magic1)+SLProfit(magic12)+SLProfit(magic2)+SLProfit(magic22)+SLProfit(magic3)+SLProfit(magic32)+SLProfit(magic4)+SLProfit(magic42); 

     double bprofits = BProfit(magic1)+BProfit(magic12)+BProfit(magic2)+BProfit(magic22)+BProfit(magic3)+BProfit(magic32)+BProfit(magic4)+BProfit(magic42);
     double sprofits = SProfit(magic1)+SProfit(magic12)+SProfit(magic2)+SProfit(magic22)+SProfit(magic3)+SProfit(magic32)+SProfit(magic4)+SProfit(magic42);

     double hbprofit = HBProfit(magic1)+HBProfit(magic12)+HBProfit(magic2)+HBProfit(magic22)+HBProfit(magic3)+HBProfit(magic32)+HBProfit(magic4)+HBProfit(magic42);
     double hsprofit = HSProfit(magic1)+HSProfit(magic12)+HSProfit(magic2)+HSProfit(magic22)+HSProfit(magic3)+HSProfit(magic32)+HSProfit(magic4)+HSProfit(magic42);
     
     double HTLots = HTotalLot(magic1)+HTotalLot(magic12)+HTotalLot(magic2)+HTotalLot(magic22)+HTotalLot(magic3)+HTotalLot(magic32)+HTotalLot(magic4)+HTotalLot(magic42);

     double TotalWinRatio = 0;
     if(horders > 0) TotalWinRatio = NormalizeDouble((hworders/horders)*100,2); 
     else TotalWinRatio = 0.00;

     double TodayOrders = TOrders(magic1)+TOrders(magic12)+TOrders(magic2)+TOrders(magic22)+TOrders(magic3)+TOrders(magic32)+TOrders(magic4)+TOrders(magic42);
     double TodayWOrders = TWOrders(magic1)+TWOrders(magic12)+TWOrders(magic2)+TWOrders(magic22)+TWOrders(magic3)+TWOrders(magic32)+TWOrders(magic4)+TWOrders(magic42);     

     double TodayWinRate = 0;
     if(TodayOrders > 0) TodayWinRate = NormalizeDouble((TodayWOrders/TodayOrders)*100,2); 
     else TodayWinRate = 0.00;     
     
     double TodayProfits = TProfits(magic1)+TProfits(magic12)+TProfits(magic2)+TProfits(magic22)+TProfits(magic3)+TProfits(magic32)+TProfits(magic4)+TProfits(magic42);  
      
     string symbolpoint = DoubleToStr(sympoint,Digits);
     string strspread = DoubleToStr(spread,Digits);
     string maxspread = DoubleToStr(MaxSpreads*mypoint*sympoint,Digits);
     double CorCond = Correlation(BaseSymbol,EntrySymbol,CorPeriod);

     ScreenStr = StringConcatenate("EA Name : ",EA_NAME," , Copyright : ",Copyrights," , EA제작일_",Create_Date," , 현재시간 : ",mytime," 평가잔액 = $",equity," Leverage_",leverage,":1, 1Lot당 필요증거금 : $",reqmargin,", Correlation : ",CorCond)+"\n";     
     ScreenStr = ScreenStr + StringConcatenate("Broker : ",broker," Server : ",servername," EA시작일_",StartDay," Next Order Lot_",orderlot1," StopLevel_",stoplevel," Freeze Level_",freeze," Stop Out_",stopout,"%, Digit_",mydigit,", Entry_", EntryEnabled)+"\n";
     ScreenStr = ScreenStr + StringConcatenate("Account Free Margin_",accfree," TickValue_",DoubleToStr(tickvalue,Digits),", TickSize_",DoubleToStr(ticksize,Digits),", Point_",symbolpoint," Min Lot_",minlot," Max Lot_",maxlot," Lot Step_",lotstep," Max Spread_",maxspread," Spread_",strspread)+"\n";
     ScreenStr = ScreenStr + "===========================================================================================================" + "\n";
     ScreenStr = ScreenStr + StringConcatenate("Filters : MM1_",DynamicMM1,", ", RiskPercent1,"%, MM2_",DynamicMM2,", ", RiskPercent2,"%, MM3_",DynamicMM3,", ", RiskPercent3,"%, MM4_",DynamicMM4,", ", RiskPercent4,"%") + "\n";
     ScreenStr = ScreenStr + StringConcatenate("Close All Filter_",CloseAllFilter,", CloseAll_TP_",All_TPs,", CloseAll_SL_",All_SLs,", Date Filter_",DateFilter," , Time Filter_",TimeFilter,", Data_",DataFilter()) + "\n";
     ScreenStr = ScreenStr + "***** 전략 1 On "+"Magic Number "+magic1+" Magic Number12 "+magic12+" ******************" + "\n";
     ScreenStr = ScreenStr + StringConcatenate("MM_Lot_",orderlot1,"_",orderlot12," TP_",XTP1," SL_",XSL1," Trailing_", TrailingStop1,", Break Even_",BreakEven1,", Break Point_",BreakPoint1)+"\n";     
     ScreenStr = ScreenStr + "***** 전략 2 On "+"Magic Number "+magic2+" Magic Number22 "+magic22+" ******************" + "\n";
     ScreenStr = ScreenStr + StringConcatenate("MM_Lot_",orderlot2,"_",orderlot22," TP_",XTP2," SL_",XSL2," Trailing_", TrailingStop2,", Break Even_",BreakEven2,", Break Point_",BreakPoint2)+"\n";     
     ScreenStr = ScreenStr + "***** 전략 3 On "+"Magic Number "+magic3+" Magic Number32 "+magic32+" ******************" + "\n";
     ScreenStr = ScreenStr + StringConcatenate("MM_Lot_",orderlot3,"_",orderlot32," TP_",XTP3," SL_",XSL3," Trailing_", TrailingStop3,", Break Even_",BreakEven3,", Break Point_",BreakPoint3)+"\n";     
     ScreenStr = ScreenStr + "***** 전략 4 On "+"Magic Number "+magic4+" Magic Number42 "+magic42+" ******************" + "\n";
     ScreenStr = ScreenStr + StringConcatenate("MM_Lot_",orderlot4,"_",orderlot42," TP_",XTP4," SL_",XSL4," Trailing_", TrailingStop4,", Break Even_",BreakEven4,", Break Point_",BreakPoint4)+"\n";     
     ScreenStr = ScreenStr + "================================================================" + "\n";
     ScreenStr = ScreenStr + StringConcatenate("전략1 : ",Profit(magic1),", New Orders : ",TotalLot(magic1),"Lot_",TotalOrders(magic1),"건 = Buy $",BProfit(magic1),"_",TotalBuyOrders(magic1),"건 / Sell $",SProfit(magic1),"_",TotalSellOrders(magic1),"건") + "\n";
     ScreenStr = ScreenStr + StringConcatenate("전략1-2 : ",Profit(magic12),", New Orders : ",TotalLot(magic12),"Lot_",TotalOrders(magic12),"건 = Buy $",BProfit(magic12),"_",TotalBuyOrders(magic12),"건 / Sell $",SProfit(magic12),"_",TotalSellOrders(magic12),"건") + "\n";
     ScreenStr = ScreenStr + StringConcatenate("전략2 : ",Profit(magic2),", New Orders : ",TotalLot(magic2),"Lot_",TotalOrders(magic2),"건 = Buy $",BProfit(magic2),"_",TotalBuyOrders(magic2),"건 / Sell $",SProfit(magic2),"_",TotalSellOrders(magic2),"건") + "\n";
     ScreenStr = ScreenStr + StringConcatenate("전략2-2 : ",Profit(magic22),", New Orders : ",TotalLot(magic22),"Lot_",TotalOrders(magic22),"건 = Buy $",BProfit(magic22),"_",TotalBuyOrders(magic22),"건 / Sell $",SProfit(magic22),"_",TotalSellOrders(magic22),"건") + "\n";
     ScreenStr = ScreenStr + StringConcatenate("전략3 : ",Profit(magic3),", New Orders : ",TotalLot(magic3),"Lot_",TotalOrders(magic3),"건 = Buy $",BProfit(magic3),"_",TotalBuyOrders(magic3),"건 / Sell $",SProfit(magic3),"_",TotalSellOrders(magic3),"건") + "\n";
     ScreenStr = ScreenStr + StringConcatenate("전략3-2 : ",Profit(magic32),", New Orders : ",TotalLot(magic32),"Lot_",TotalOrders(magic32),"건 = Buy $",BProfit(magic32),"_",TotalBuyOrders(magic32),"건 / Sell $",SProfit(magic32),"_",TotalSellOrders(magic32),"건") + "\n";
     ScreenStr = ScreenStr + StringConcatenate("전략4 : ",Profit(magic4),", New Orders : ",TotalLot(magic4),"Lot_",TotalOrders(magic4),"건 = Buy $",BProfit(magic4),"_",TotalBuyOrders(magic4),"건 / Sell $",SProfit(magic4),"_",TotalSellOrders(magic4),"건") + "\n";
     ScreenStr = ScreenStr + StringConcatenate("전략4-2 : ",Profit(magic42),", New Orders : ",TotalLot(magic42),"Lot_",TotalOrders(magic42),"건 = Buy $",BProfit(magic42),"_",TotalBuyOrders(magic42),"건 / Sell $",SProfit(magic42),"_",TotalSellOrders(magic42),"건") + "\n";
     ScreenStr = ScreenStr + "================================================================" + "\n";
     ScreenStr = ScreenStr + StringConcatenate("총현재오더 : ",profits,", New Orders : ",TlLots,"Lot_",orders,"건 = Buy $",bprofits,"_",borders,"건 / Sell $",sprofits,"_",sorders,"건, 금일 승률_",TodayWinRate,"% 금일 수익_$",TodayProfits) + "\n";
     ScreenStr = ScreenStr + "================================================================" + "\n";
     ScreenStr = ScreenStr + StringConcatenate("전략1 과거 : ",HistoryProfit(magic1),", New Orders : ",HTotalLot(magic1),"Lot_",HWBuyOrders(magic1)+HWSellOrders(magic1),"/",HOrders(magic1),"건 = Buy $",HBProfit(magic1),"_",HWBuyOrders(magic1),"/",HBuyOrders(magic1),"건 / Sell $",HSProfit(magic1),"_",HWSellOrders(magic1),"/",HSellOrders(magic1),"건, 승률_",WinRatio(magic1),"%") + "\n";
     ScreenStr = ScreenStr + StringConcatenate("전략1-2 과거 : ",HistoryProfit(magic12),", New Orders : ",HTotalLot(magic12),"Lot_",HWBuyOrders(magic12)+HWSellOrders(magic12),"/",HOrders(magic12),"건 = Buy $",HBProfit(magic12),"_",HWBuyOrders(magic12),"/",HBuyOrders(magic12),"건 / Sell $",HSProfit(magic12),"_",HWSellOrders(magic12),"/",HSellOrders(magic12),"건, 승률_",WinRatio(magic12),"%") + "\n";
     ScreenStr = ScreenStr + StringConcatenate("전략2 과거 : ",HistoryProfit(magic2),", New Orders : ",HTotalLot(magic2),"Lot_",HWBuyOrders(magic2)+HWSellOrders(magic2),"/",HOrders(magic2),"건 = Buy $",HBProfit(magic2),"_",HWBuyOrders(magic2),"/",HBuyOrders(magic2),"건 / Sell $",HSProfit(magic2),"_",HWSellOrders(magic2),"/",HSellOrders(magic2),"건, 승률_",WinRatio(magic2),"%") + "\n";
     ScreenStr = ScreenStr + StringConcatenate("전략2-2 과거 : ",HistoryProfit(magic22),", New Orders : ",HTotalLot(magic22),"Lot_",HWBuyOrders(magic22)+HWSellOrders(magic22),"/",HOrders(magic22),"건 = Buy $",HBProfit(magic22),"_",HWBuyOrders(magic22),"/",HBuyOrders(magic22),"건 / Sell $",HSProfit(magic22),"_",HWSellOrders(magic22),"/",HSellOrders(magic22),"건, 승률_",WinRatio(magic22),"%") + "\n";
     ScreenStr = ScreenStr + StringConcatenate("전략3 과거 : ",HistoryProfit(magic3),", New Orders : ",HTotalLot(magic3),"Lot_",HWBuyOrders(magic3)+HWSellOrders(magic3),"/",HOrders(magic3),"건 = Buy $",HBProfit(magic3),"_",HWBuyOrders(magic3),"/",HBuyOrders(magic3),"건 / Sell $",HSProfit(magic3),"_",HWSellOrders(magic3),"/",HSellOrders(magic3),"건, 승률_",WinRatio(magic3),"%") + "\n";
     ScreenStr = ScreenStr + StringConcatenate("전략3-2 과거 : ",HistoryProfit(magic32),", New Orders : ",HTotalLot(magic32),"Lot_",HWBuyOrders(magic32)+HWSellOrders(magic32),"/",HOrders(magic32),"건 = Buy $",HBProfit(magic32),"_",HWBuyOrders(magic32),"/",HBuyOrders(magic32),"건 / Sell $",HSProfit(magic32),"_",HWSellOrders(magic32),"/",HSellOrders(magic32),"건, 승률_",WinRatio(magic32),"%") + "\n";
     ScreenStr = ScreenStr + StringConcatenate("전략4 과거 : ",HistoryProfit(magic4),", New Orders : ",HTotalLot(magic4),"Lot_",HWBuyOrders(magic4)+HWSellOrders(magic4),"/",HOrders(magic4),"건 = Buy $",HBProfit(magic4),"_",HWBuyOrders(magic4),"/",HBuyOrders(magic4),"건 / Sell $",HSProfit(magic4),"_",HWSellOrders(magic4),"/",HSellOrders(magic4),"건, 승률_",WinRatio(magic4),"%") + "\n";
     ScreenStr = ScreenStr + StringConcatenate("전략4-2 과거 : ",HistoryProfit(magic42),", New Orders : ",HTotalLot(magic42),"Lot_",HWBuyOrders(magic42)+HWSellOrders(magic42),"/",HOrders(magic42),"건 = Buy $",HBProfit(magic42),"_",HWBuyOrders(magic42),"/",HBuyOrders(magic42),"건 / Sell $",HSProfit(magic42),"_",HWSellOrders(magic42),"/",HSellOrders(magic42),"건, 승률_",WinRatio(magic42),"%") + "\n";
     ScreenStr = ScreenStr + "================================================================" + "\n";     
     ScreenStr = ScreenStr + StringConcatenate("총매수수익 : $",wbprofit,", 총매도수익 : $",wsprofit,", 총매수손실 : $ ",lbprofit,", 총매도손실 : $ ",lsprofit) + "\n";
     ScreenStr = ScreenStr + StringConcatenate("전체 과거 : $",hprofit,", Buy : $",hbprofit,", Sell : $",hsprofit,", Total Orders : ",HTLots,"Lot_",hwborders+hwsorders,"/",horders,"건 = Total Buy ",hwborders,"/",hborders,"건 / Total Sell ",hwsorders,"/",hsorders,"건, 승률_",TotalWinRatio,"%");
     Comment(ScreenStr);
 
     return(0);

}    // EA 종료


//******************************************************************************
//| EA Valid Check Function                                                    |
//******************************************************************************

bool CheckValid() {  

   if (!IsDemo() && !AccountNumber()==AccNumber01 && !AccountNumber()==AccNumber02 && !AccountNumber()==AccNumber03) {
       Alert("좋은 말할 때 돈내고 쓰세요!");  
       return(FALSE); 
   }
   else return(TRUE); 
}     

//******************************************************************************
//| Data Filter Function                                                       |
//******************************************************************************
// 데이타 다운로드 미비에 의한 오류계산 방지 로직

bool DataFilter() {  

   if(iBars(Symbol(), 1) < MinBars || iBars(Symbol(), 5) < MinBars || iBars(Symbol(), 15) < MinBars ) {
     return(FALSE);
   }
   else return(TRUE);
}   

//******************************************************************************
// Max Spread Limitation 설정함수                                              |
//******************************************************************************

bool TradeEnable() {
    if(ask00-bid00 > MaxSpreads*mypoint*sympoint) return(false);
    else return(true);
   }
   
//******************************************************************************
//| 주문 함수 (OpenOrder)                                                      |
//******************************************************************************

int OpenOrder(string SymbolName, int CmdType, double Lots, int Slippages, double StopLosses, double TakeProfit, string Commented, int magic) {   // 함수 시작

  static string OrderTypeToString[6] = {"OP_BUY", "OP_SELL", "OP_BUYLIMIT", "OP_SELLLIMIT", "OP_BUYSTOP", "OP_SELLSTOP"};
  
  int Ticket = -1;
  int ErrorCodes;

  int Slips = 0;
  double Vol = 0;
  string Comments;
  color CLRs;
  
  double stopbuy = ask00-(StopLosses*mypoint*sympoint);
  double stopsell = bid00+(StopLosses*mypoint*sympoint);
  double tpbuy = ask00+(TakeProfit*mypoint*sympoint);
  double tpsell = bid00-(TakeProfit*mypoint*sympoint);
   
  if (StopLosses == 0) {
      stopbuy = 0;    
      stopsell = 0;
  }
  else
  if (StopLosses < MathMax(stoplevel,freeze)) {
      stopbuy = MathMax(stoplevel,freeze);    
      stopsell = MathMax(stoplevel,freeze);
  }      
      
  if (TakeProfit == 0) {
      tpbuy = 0;
      tpsell = 0;
  }
  else
  if (TakeProfit < MathMax(stoplevel,freeze)) {
      tpbuy = MathMax(stoplevel,freeze);    
      tpsell = MathMax(stoplevel,freeze);
  } 

  if (StopLosses == 0 && TakeProfit == 0) ECN = FALSE;
      
  if (CmdType == OP_BUY) {   // Buy 시작
      Comments = Commentary+"_"+Commented+"_샀어";
      CLRs = Red;

  if (ECN == true) {  // ECN 시작

    double execution = GetTickCount(); 
    Ticket = OrderSend(SymbolName, CmdType, Lots, ask00, Slippages, 0, 0,Comments,magic,0,CLRs);
    if(SoundEnabled1) PlaySound(sound1);

    if(Ticket == -1) {  // check for errors
    ErrorCodes = GetLastError();
    Print("아씨!, Error: " + ErrorDescription(ErrorCodes));
    return(-1);
    }  // check for errors

    OrderSelect(Ticket, SELECT_BY_TICKET);

    if (!OrderSelect(Ticket, SELECT_BY_TICKET)) {  // check for errors
    ErrorCodes = GetLastError();
    Print("아씨!, Error: " + ErrorDescription(ErrorCodes));
    return(-1);
    }  // check for errors

    OrderModify(Ticket,OrderOpenPrice(),stopbuy,tpbuy,0,CLRs);
    execution = GetTickCount()-execution; 
    return(0);
    }    // ECN 종료
  else
    {   // No ECN 

    execution = GetTickCount(); 
    Ticket = OrderSend(SymbolName, CmdType, Lots, ask00, Slippages, stopbuy, tpbuy,Comments,magic,0,CLRs);  
    if(SoundEnabled1) PlaySound(sound1);
    
    if(Ticket == -1) {  // check for errors
    ErrorCodes = GetLastError();
    Print("아씨!, Error: " + ErrorDescription(ErrorCodes));
    return(-1);
      }  // check for errors
    execution = GetTickCount()-execution; 

    return(0);
    }  // No ECN 종료
  }  // Buy 종료

  else

  if (CmdType == OP_SELL) {    // Sell 시작
      Comments = Commentary+"_"+Commented+"_팔았어";
      CLRs = Blue;

     if (ECN == true) {  // ECN 시작

       execution = GetTickCount(); 
       Ticket = OrderSend(SymbolName, CmdType, Lots, bid00, Slippages, 0, 0,Comments,magic,0,CLRs);
       if(SoundEnabled2) PlaySound(sound2);       

       if(Ticket == -1) {   // check for errors
       ErrorCodes = GetLastError();
       Print("아씨!, Error: " + ErrorDescription(ErrorCodes));
       return(-1);
       }     // check for errors

       OrderSelect(Ticket, SELECT_BY_TICKET);

       if (!OrderSelect(Ticket, SELECT_BY_TICKET)) {    // check for errors
       ErrorCodes = GetLastError();
       Print("아씨!, Error: " + ErrorDescription(ErrorCodes));
       return(-1);
       }     // check for errors

       OrderModify(Ticket,OrderOpenPrice(),stopsell, tpsell,0,CLRs);
       execution = GetTickCount()-execution; 
       return(0);

       }   // ECN 종료
      else
       {  // No ECN 

       execution = GetTickCount(); 
       Ticket = OrderSend(SymbolName, CmdType, Lots, bid00, Slippages, stopsell, tpsell,Comments,magic,0,CLRs);
       if(SoundEnabled2) PlaySound(sound2);

       if(Ticket == -1) {     // check for errors
       ErrorCodes = GetLastError();
       Print("아씨!, Error: " + ErrorDescription(ErrorCodes));
       return(-1);
       }  // check for errors

       execution = GetTickCount()-execution; 
       return(0);

       }  // No ECN 종료
     }  // Sell 종료

  OrderSelect(OrdersTotal() - 1, SELECT_BY_POS, MODE_TRADES);
                     
    if (OrderSymbol() == SymbolName)  
    {
      Slips = OrderSlipPage(OrderOpenPrice());
      Ticket = OrderTicket();
      Vol = OrderLots();
    }
    
  Print(Ticket, " = OrderSend( ", Comments,", ", SymbolName, ", ", OrderTypeToString[CmdType], ", ", Lots, ", ", DoubleToStr(OrderOpenPrice(), MarketInfo(SymbolName, MODE_DIGITS)),", Execution : ",execution,"ms",
        ", ", Slippages, ", ", StopLosses, ", ", TakeProfit, ") - ", ErrorDescription(ErrorCodes), ", SlipPage = ", Slips, ", Lots = ", Vol);
        
  return(Ticket);
}  // 함수 종료


//******************************************************************************
//| Slippage 계산 함수                                                         |
//******************************************************************************

int OrderSlipPage( double OriginalPrice )
{
  double Tmp;
  int Res;
  
  if (OrderCloseTime() == 0)
  {
    if (OrderType() == OP_BUY)
      Tmp = OriginalPrice - OrderOpenPrice();
    else if (OrderType() == OP_SELL)
      Tmp = OrderOpenPrice() - OriginalPrice;
  }
  else
  {
    if (OrderType() == OP_BUY)
      Tmp = OrderClosePrice() - OriginalPrice;
    else if (OrderType() == OP_SELL)
      Tmp = OriginalPrice - OrderClosePrice();
  }
  
  if (Tmp > 0)
    Res = Tmp / MarketInfo(OrderSymbol(), MODE_POINT) + 0.1;
  else
    Res = Tmp / MarketInfo(OrderSymbol(), MODE_POINT) - 0.1;
  
  return(Res);
}   

//******************************************************************************
//| OrderLot Calculate Function(총Lot 계산 함수)                               |
//******************************************************************************

 double TotalLot(int Magic) {  // 0
 double TLot=0;
 for (int k=0; k < OrdersTotal(); k++)  {  // 1
  if (OrderSelect(k, SELECT_BY_POS, MODE_TRADES))  {  // 2
   if (OrderMagicNumber()==Magic)  {  // 3
       TLot = NormalizeDouble(TLot + OrderLots(),2);
       }  // 3
    }   // 2
  }   // 1
  return(TLot);
}  // 0

//******************************************************************************
//| Historical OrderLot Calculate Function(과거 총Lot 계산 함수)               |
//******************************************************************************

 double HTotalLot(int Magic) {  // 0
 double TLot=0;
 for (int k=0; k < OrdersHistoryTotal(); k++)  {  // 1
  if (OrderSelect(k, SELECT_BY_POS, MODE_HISTORY))  {  // 2
   if (OrderMagicNumber()==Magic)  {  // 3
       TLot = NormalizeDouble(TLot + OrderLots(),2);
       }  // 3
    }   // 2
  }   // 1
  return(TLot);
}  // 0

//******************************************************************************
//| Profit Calculate Function(수익 계산 함수)                                  |
//******************************************************************************

 double Profit(int Magic) {  // 0
 double Prof=0;
 for (int k=0; k < OrdersTotal(); k++)  {  // 1
  if (OrderSelect(k, SELECT_BY_POS, MODE_TRADES))  {  // 2
   if (OrderMagicNumber()==Magic)  {  // 3
       Prof = NormalizeDouble(Prof + OrderProfit()+OrderSwap()+OrderCommission(),2);
       }  // 3
    }   // 2
  }   // 1
  return(Prof);
}  // 0

//******************************************************************************
//| 총매수수익 계산 함수                                                       |
//******************************************************************************

 double BProfit(int Magic) {  // 0
 double Prof=0;
 for (int k=0; k < OrdersTotal(); k++)  {  // 1
  if (OrderSelect(k, SELECT_BY_POS, MODE_TRADES))  {  // 2
   if (OrderMagicNumber()==Magic && OrderType()==OP_BUY)  {  // 3
       Prof = NormalizeDouble(Prof + OrderProfit()+OrderSwap()+OrderCommission(),2);
       }  // 3
    }   // 2
  }   // 1
  return(Prof);
}  // 0

//******************************************************************************
//| 총매도수익 계산 함수                                                       |
//******************************************************************************

 double SProfit(int Magic) {  // 0
 double Prof=0;
 for (int k=0; k < OrdersTotal(); k++)  {  // 1
  if (OrderSelect(k, SELECT_BY_POS, MODE_TRADES))  {  // 2
   if (OrderMagicNumber()==Magic && OrderType()==OP_SELL) {  // 3
       Prof = NormalizeDouble(Prof + OrderProfit()+OrderSwap()+OrderCommission(),2);
       }  // 3
    }   // 2
  }   // 1
  return(Prof);
}  // 0

//******************************************************************************
//| Total order Calculate Function(총오더수 계산 함수)                         |
//******************************************************************************

int TotalOrders(int MAGIC) {  // 0
 int cnt=0;
 for (int i=0; i < OrdersTotal(); i++)  {  // 1
   if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {  // 2
    if (OrderMagicNumber()==MAGIC && (OrderType()==OP_BUY || OrderType()==OP_SELL))  {  // 3
      cnt++;
      }  // 3
    }  // 2
  }   // 1
  return(cnt);
}  // 0

//******************************************************************************
//| Total Buy order Calculate Function(총매수 계약 계산 함수)                  |
//******************************************************************************

int TotalBuyOrders(int MAGIC) {  // 0
 int cnt=0;
 for (int i=0; i < OrdersTotal(); i++)  {  // 1
   if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {  // 2
    if ( OrderMagicNumber()==MAGIC && OrderType()==OP_BUY )  {  // 3
      cnt++;
      }  // 3
    }  // 2
  }   // 1 
  return(cnt);
}  // 0

//******************************************************************************
//| Total Sell order Calculate Function(총매도 계약 계산 함수)                 |
//******************************************************************************

int TotalSellOrders(int MAGIC) {  // 0
 int cnt=0;
 for (int i=0; i < OrdersTotal(); i++)  {  // 1
   if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))  {  // 2
     if ( OrderMagicNumber()==MAGIC && OrderType()==OP_SELL )  {  // 3
      cnt++;
      }  // 3
    }   // 2
  }   // 1
  return(cnt);
}  // 0

//******************************************************************************
//| 총수익 계산 함수(과거치 포함)                                              |
//******************************************************************************

 double HistoryProfit(int Magic) {  // 0
 double Prof=0;
 for (int k=0; k < OrdersHistoryTotal(); k++)  {  // 1
  if (OrderSelect(k, SELECT_BY_POS, MODE_HISTORY))  {  // 2
   if (OrderMagicNumber()==Magic) {  // 3
       Prof = NormalizeDouble(Prof + OrderProfit()+OrderSwap()+OrderCommission(),2);
       }  // 3
    }   // 2
  }   // 1
  return(Prof);
}  // 0


//******************************************************************************
//| 총매수수익 계산 함수(과거치 포함)                                          |
//******************************************************************************

 double HBProfit(int Magic) {  // 0
 double Prof=0;
 for (int k=0; k < OrdersHistoryTotal(); k++)  {  // 1
  if (OrderSelect(k, SELECT_BY_POS, MODE_HISTORY))  {  // 2
   if (OrderMagicNumber()==Magic && OrderType()==OP_BUY)  {  // 3
       Prof = NormalizeDouble(Prof + OrderProfit()+OrderSwap()+OrderCommission(),2);
       }  // 3
    }   // 2
  }   // 1
  return(Prof);
}  // 0

//******************************************************************************
//| 총매도수익 계산 함수(과거치 포함)                                          |
//******************************************************************************

 double HSProfit(int Magic) {  // 0
 double Prof=0;
 for (int k=0; k < OrdersHistoryTotal(); k++)  {  // 1
  if (OrderSelect(k, SELECT_BY_POS, MODE_HISTORY))  {  // 2
   if (OrderMagicNumber()==Magic && OrderType()==OP_SELL) {  // 3
       Prof = NormalizeDouble(Prof + OrderProfit()+OrderSwap()+OrderCommission(),2);
       }  // 3
    }   // 2
  }   // 1
  return(Prof);
}  // 0

//******************************************************************************
//| Total order Calculate Function(총오더수 계산 함수,과거치 포함)             |
//******************************************************************************

double HOrders(int MAGIC) {  // 0
 int cnt=0;
 for (int i=0; i < OrdersHistoryTotal(); i++)  {  // 1
   if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY))  {  // 2
    if (OrderMagicNumber()==MAGIC && (OrderType()==OP_BUY || OrderType()==OP_SELL)) {  // 3
      cnt++;
      }  // 3
    }  // 2
  }   // 1
  return(cnt);
}  // 0

//******************************************************************************
//| 총Buy오더수 계산 함수(과거치 포함)                                         |
//******************************************************************************

int HBuyOrders(int MAGIC) {  // 0
 int cnt=0;
 for (int i=0; i < OrdersHistoryTotal(); i++)  {  // 1
   if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) {  // 2
    if (OrderMagicNumber()==MAGIC && OrderType()==OP_BUY)  {  // 3
      cnt++;
      }  // 3
    }  // 2
  }   // 1
  return(cnt);
}  // 0

//******************************************************************************
//| 총Sell오더수 계산 함수(과거치 포함)                                        |
//******************************************************************************

int HSellOrders(int MAGIC)  {  // 0
 int cnt=0;
 for (int i=0; i < OrdersHistoryTotal(); i++)  {  // 1
   if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY))  {  // 2
    if (OrderMagicNumber()==MAGIC && OrderType()==OP_SELL)   {  // 3
      cnt++;
      }  // 3
    }  // 2
  }   // 1
  return(cnt);
}  // 0

//******************************************************************************
//| 총Winning Buy오더수 계산 함수(과거치 포함)                                 |
//******************************************************************************

double HWBuyOrders(int MAGIC) {  // 0
 int cnt=0;
 for (int i=0; i < OrdersHistoryTotal(); i++)  {  // 1
   if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) {  // 2
    if (OrderMagicNumber()==MAGIC && OrderType()==OP_BUY)  {  // 3
      if(OrderProfit()+OrderSwap()+OrderCommission() >= 0) {  // 4
      cnt++;
       }  // 4
      }  // 3
    }  // 2
  }   // 1
  return(cnt);
}  // 0

//******************************************************************************
//| 총Winning Sell오더수 계산 함수(과거치 포함)                                |
//******************************************************************************

double HWSellOrders(int MAGIC)  {  // 0
 int cnt=0;
 for (int i=0; i < OrdersHistoryTotal(); i++)  {  // 1
   if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY))  {  // 2
    if (OrderMagicNumber()==MAGIC && OrderType()==OP_SELL)   {  // 3
      if(OrderProfit()+OrderSwap()+OrderCommission() >= 0) {  // 4    
      cnt++;
       }  // 4       
      }  // 3
    }  // 2
  }   // 1
  return(cnt);
}  // 0

//******************************************************************************
//| Win Ratio 계산 함수(과거치 포함)                                           |
//******************************************************************************

double WinRatio(int MAGIC)  {  // 0

  double WinR = 0;
  if(HOrders(MAGIC) == 0) WinR = 0;
  else WinR = NormalizeDouble(((HWBuyOrders(MAGIC)+HWSellOrders(MAGIC))/HOrders(MAGIC))*100,1);
  
  return(WinR);
}  

//******************************************************************************
//| Total order Calculate Function(금일오더수 계산 함수)                       |
//******************************************************************************

double TOrders(int MAGIC) {  // 0
 int cnt=0;
 
 for (int i=0; i < OrdersHistoryTotal(); i++)  {  // 1
   if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY))  {  // 2
    if (OrderMagicNumber()==MAGIC && (OrderType()==OP_BUY || OrderType()==OP_SELL)) {  // 3
      if(TimeYear(Time[0])==TimeYear(OrderCloseTime()) && TimeMonth(Time[0])==TimeMonth(OrderCloseTime()) && TimeDay(Time[0])==TimeDay(OrderCloseTime())) { // 4 
      cnt++;
        }  // 4
      }  // 3
    }  // 2
  }   // 1
  return(cnt);
}  // 0

//******************************************************************************
//| 총Winning 오더수 계산 함수(금일)                                           |
//******************************************************************************

double TWOrders(int MAGIC) {  // 0
 int cnt=0;
  
 for (int i=0; i < OrdersHistoryTotal(); i++)  {  // 1
   if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) {  // 2
    if (OrderMagicNumber()==MAGIC && (OrderType()==OP_BUY || OrderType()==OP_SELL))  {  // 3
      if(TimeYear(Time[0])==TimeYear(OrderCloseTime()) && TimeMonth(Time[0])==TimeMonth(OrderCloseTime()) && TimeDay(Time[0])==TimeDay(OrderCloseTime())) { // 4  
        if(OrderProfit()+OrderSwap()+OrderCommission() >= 0) {  // 5
           cnt++;
         }  // 5           
       }  // 4
      }  // 3
    }  // 2
  }   // 1
  return(cnt);
}  // 0

/*
//******************************************************************************
//| Win Ratio 계산 함수(금일)                                                  |
//******************************************************************************

double TWinRate(int MAGIC)  {  // 0

  double WinR = 0;
  if(TOrders(MAGIC) > 0) WinR = NormalizeDouble((TWOrders(MAGIC)/TOrders(MAGIC))*100,2);
  else WinR = 0.00;
  
  return(WinR);
}  
*/

//******************************************************************************
//| 금일 수익 계산 함수                                                        |
//******************************************************************************

double TProfits(int MAGIC) {  // 0
 double Prof = 0.0; 

 for (int i=0; i < OrdersHistoryTotal(); i++)  {  // 1
   if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) {  // 2
    if (OrderMagicNumber()==MAGIC && (OrderType()==OP_BUY || OrderType()==OP_SELL))  {  // 3
      if(TimeYear(Time[0])==TimeYear(OrderCloseTime()) && TimeMonth(Time[0])==TimeMonth(OrderCloseTime()) && TimeDay(Time[0])==TimeDay(OrderCloseTime())) { // 4  
         Prof = NormalizeDouble(Prof + OrderProfit()+OrderSwap()+OrderCommission(),2);
       }  // 4
      }  // 3
    }  // 2
  }   // 1
  return(Prof);
}  // 0

//******************************************************************************
//| 총Win매수수익 계산 함수(과거치 포함)                                       |
//******************************************************************************

 double BWProfit(int Magic) {  // 0
 double Prof=0;
 for (int k=0; k < OrdersHistoryTotal(); k++)  {  // 1
   if (OrderSelect(k, SELECT_BY_POS, MODE_HISTORY))  {  // 2
     if (OrderMagicNumber()==Magic && OrderType()==OP_BUY)  {  // 3
       if(OrderProfit()+OrderSwap()+OrderCommission() >= 0)  {   // 4       
         Prof = NormalizeDouble(Prof+OrderProfit()+OrderSwap()+OrderCommission(),2);
        }  // 4
       }  // 3
    }   // 2
  }   // 1
  return(Prof);
}  // 0

//******************************************************************************
//| 총Win매도수익 계산 함수(과거치 포함)                                       |
//******************************************************************************

 double SWProfit(int Magic) {  // 0
 double Prof=0;
 for (int k=0; k < OrdersHistoryTotal(); k++)  {  // 1
  if (OrderSelect(k, SELECT_BY_POS, MODE_HISTORY))  {  // 2
    if (OrderMagicNumber()==Magic && OrderType()==OP_SELL) {  // 3
       if(OrderProfit()+OrderSwap()+OrderCommission() >= 0) {  // 4   
         Prof = NormalizeDouble(Prof+OrderProfit()+OrderSwap()+OrderCommission(),2);
         }  // 4
       }  // 3
    }   // 2
  }   // 1
  return(Prof);
}  // 0


//******************************************************************************
//| 총Loss매수수익 계산 함수(과거치 포함)                                      |
//******************************************************************************

 double BLProfit(int Magic) {  // 0
 double Prof=0;
 for (int k=0; k < OrdersHistoryTotal(); k++)  {  // 1
   if (OrderSelect(k, SELECT_BY_POS, MODE_HISTORY))  {  // 2
     if (OrderMagicNumber()==Magic && OrderType()==OP_BUY)  {  // 3
       if(OrderProfit()+OrderSwap()+OrderCommission() < 0) {   // 4       
         Prof = NormalizeDouble(Prof+OrderProfit()+OrderSwap()+OrderCommission(),2);
        }  // 4
       }  // 3
    }   // 2
  }   // 1
  return(Prof);
}  // 0

//******************************************************************************
//| 총Loss매도수익 계산 함수(과거치 포함)                                      |
//******************************************************************************

 double SLProfit(int Magic) {  // 0
 double Prof=0;
 for (int k=0; k < OrdersHistoryTotal(); k++)  {  // 1
  if (OrderSelect(k, SELECT_BY_POS, MODE_HISTORY))  {  // 2
    if (OrderMagicNumber()==Magic && OrderType()==OP_SELL) {  // 3
       if(OrderProfit()+OrderSwap()+OrderCommission() < 0) {  // 4   
         Prof = NormalizeDouble(Prof+OrderProfit()+OrderSwap()+OrderCommission(),2);
         }  // 4
       }  // 3
    }   // 2
  }   // 1
  return(Prof);
}  // 0


//******************************************************************************
//| Trailing Stop Function                                                     |
//******************************************************************************

void MoveTrailingStop(int Magics,double TrailingStop) {
   int ct,totl=OrdersTotal();
   
   if (OrdersTotal() > 0) {
   for(ct=0;ct<totl;ct++) {
      OrderSelect(ct,SELECT_BY_POS,MODE_TRADES);
      if(OrderType()==OP_BUY && OrderSymbol()==Symbol() && OrderMagicNumber()==Magics)  {
            if( TrailingStop>0 && bid00 > NormalizeDouble(OrderOpenPrice()+TrailingStop*mypoint*sympoint,Digits) )  {                 
               if((NormalizeDouble(OrderStopLoss(),Digits)<NormalizeDouble(bid00-TrailingStop*mypoint*sympoint,Digits))||(OrderStopLoss()==0))  {
                  OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(bid00-TrailingStop*mypoint*sympoint,Digits),OrderTakeProfit(),0,Blue);
                  return(0);
               }
            }
         }
      if(OrderType()==OP_SELL && OrderSymbol()==Symbol() && OrderMagicNumber()==Magics) {
            if( TrailingStop>0 && ask00 < NormalizeDouble(OrderOpenPrice()-TrailingStop*mypoint*Point,Digits) )  {                 
               if((NormalizeDouble(OrderStopLoss(),Digits)>(NormalizeDouble(ask00+TrailingStop*mypoint*sympoint,Digits)))||(OrderStopLoss()==0)) {
                  OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(ask00+TrailingStop*mypoint*sympoint,Digits),OrderTakeProfit(),0,Red);
                  return(0);
            }
          }
        }
      }
   }
}

//******************************************************************************
//| Break Even Strategy                                                        |
//******************************************************************************

void MoveBreakEven(int Magics,double BreakEven,double BreakPoint) {
   int cnt,total=OrdersTotal();

   if (OrdersTotal() > 0) {
   for(cnt=0;cnt<total;cnt++) {
      OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);

      if( OrderType()<=OP_SELL && OrderSymbol()==Symbol() && OrderMagicNumber()==Magics ) {
         if(OrderType()==OP_BUY) {
            if(BreakEven>0) {
               if(NormalizeDouble((bid00-OrderOpenPrice()),Digits) > BreakEven*mypoint*sympoint) {
                  if(NormalizeDouble((OrderStopLoss()-OrderOpenPrice()),Digits) < 0)  {
                     OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(OrderOpenPrice()+BreakPoint*mypoint*sympoint,Digits),OrderTakeProfit(),0,Blue);
                     return(0);
                  }
               }
            }
         }
         else
         {
            if(BreakEven>0) {
               if(NormalizeDouble((OrderOpenPrice()-ask00),Digits) > BreakEven*mypoint*sympoint) {
                  if(NormalizeDouble((OrderOpenPrice()-OrderStopLoss()),Digits) < 0) {
                     OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(OrderOpenPrice()-BreakPoint*mypoint*sympoint,Digits),OrderTakeProfit(),0,Red);
                     return(0);
                     }
                  }
               }
          }
        }
      }
   }
}

//******************************************************************************
//| Stop Out조건발생시 전체 일괄 청산 함수                                     |
//******************************************************************************

void StopOutClose() {  // 0
 
  bool CloseAllOrders = false;

  if(AccountFreeMargin() < StopOutBalance || AccountBalance() < StopOutBalance) CloseAllOrders = true;
    else CloseAllOrders = false;
  
    if(CloseAllOrders) {  // 15

      int totalord = OrdersTotal();

      for(int jk=totalord-1;jk >= 0;jk--)  {  // 16

         OrderSelect(jk, SELECT_BY_POS, MODE_TRADES);
         int types = OrderType();
         bool resultall = false;
         RefreshRates();

     switch(types) {   //switch

             case OP_BUY : resultall = OrderClose(OrderTicket(),OrderLots(),bid00,5,Red);
             break;

             case OP_SELL : resultall = OrderClose(OrderTicket(),OrderLots(),ask00,5, Blue);
             }    //switch

     if(resultall == false) {  // 17
     Print("Order ", OrderTicket(), " failed to close. Error:", GetLastError() );
                         }  // 17

       }  // 16
   }   // 15
}  // 0

//******************************************************************************
//| 통화별 매직넘버 설정                                                       |
//******************************************************************************

int getmagic() {

// 접미사형태의 통화대처를 위해 심볼명의 6자리까지 심볼명으로 지정

      NowSym = StringSubstr(Symbol(), 0, 6);

      if(NowSym == "EURUSD") magic1 = 120903001;
      if(NowSym == "GBPUSD") magic1 = 120903002;
      if(NowSym == "USDJPY") magic1 = 120903003;
      if(NowSym == "AUDUSD") magic1 = 120903004;
      if(NowSym == "EURGBP") magic1 = 120903005;
      if(NowSym == "USDCAD") magic1 = 120903006;
      if(NowSym == "USDCHF") magic1 = 120903007;
      if(NowSym == "CHFJPY") magic1 = 120903008;
      if(NowSym == "EURJPY") magic1 = 120903009;
      if(NowSym == "NZDUSD") magic1 = 120903010;
      if(NowSym == "GBPJPY") magic1 = 120903011;
      if(NowSym == "EURAUD") magic1 = 120903012;
      if(NowSym == "EURCAD") magic1 = 120903013;
      if(NowSym == "EURCHF") magic1 = 120903014;
      if(NowSym == "CADJPY") magic1 = 120903015;
      if(NowSym == "AUDNZD") magic1 = 120903016;
      if(NowSym == "AUDCAD") magic1 = 120903017;
      if(NowSym == "AUDCHF") magic1 = 120903018;
      if(NowSym == "AUDJPY") magic1 = 120903019;
      if(NowSym == "GBPAUD") magic1 = 120903020;      
      if(NowSym == "NZDJPY") magic1 = 120903021;
      if(NowSym == "GBPCAD") magic1 = 120903022;
      if(NowSym == "NZDCAD") magic1 = 120903023;
      if(NowSym == "CADCHF") magic1 = 120903024;
      if(NowSym == "GBPNZD") magic1 = 120903025;
      if(NowSym == "EURNZD") magic1 = 120903026;
      if(NowSym == "NZDCHF") magic1 = 120903027;
      if(NowSym == "GBPCHF") magic1 = 120903028;

   return(magic1);
}

//******************************************************************************
//| Close Buy By Magic Number                                                  |
//******************************************************************************
void CloseBuyOpens(int Magic) {    // 함수 시작  
 
    int total = OrdersTotal();
    for(int i=total-1;i>=0;i--)  {   // Loop 시작
      OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
      int type   = OrderType();
      bool result = false;
   
       if (OrderMagicNumber() == Magic && type == OP_BUY) {  // magic 조건시작
       RefreshRates();
         result = OrderClose( OrderTicket(), OrderLots(), bid00, slippage, Blue );
         if(SoundEnabled3) PlaySound(sound3);
         
         if(result == false) {  // 에러 처리
           Alert("Order " , OrderTicket() , " failed to close. Error:" , GetLastError() );
           Sleep(3000);
          }   // 에러 처리 종료
       }    // magic 조건종료
     }    // Loop 종료
}     // 함수 종료  

//******************************************************************************
//| Close Sell By Magic Number                                                 |
//******************************************************************************
void CloseSellOpens(int Magic) {    // 함수 시작  
 
    int total = OrdersTotal();
    for(int i=total-1;i>=0;i--)  {   // Loop 시작
      OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
      int type   = OrderType();
      bool result = false;
   
       if (OrderMagicNumber() == Magic && type == OP_SELL) {  // magic 조건시작
       RefreshRates();
         result = OrderClose( OrderTicket(), OrderLots(), ask00, slippage, Red );
         if(SoundEnabled4) PlaySound(sound4);
                  
         if(result == false) {  // 에러 처리
           Alert("Order " , OrderTicket() , " failed to close. Error:" , GetLastError() );
           Sleep(3000);
          }   // 에러 처리 종료
       }    // magic 조건종료
     }    // Loop 종료
}     // 함수 종료  


//******************************************************************************
//| Find Last Buy Price Function                                               |
//******************************************************************************

double FindLastBuyPrice(int Magics) {

   double ord_open_price;
   int ord_ticket;
   double buffers = 0;
   int ticket_compair = -1;

   for (int cnt = 0; cnt < OrdersTotal(); cnt++) {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if (OrderSymbol() != Symbol() || OrderMagicNumber() != Magics) continue;

      if (OrderSymbol() == Symbol() && OrderMagicNumber() == Magics) {

         ord_ticket = OrderTicket();
         if (ord_ticket > ticket_compair) {
            ord_open_price = OrderOpenPrice();
            buffers = ord_open_price;
            ticket_compair = ord_ticket;
         }
      }
   }
   return (ord_open_price);
}

//******************************************************************************
//| Find Last Sell Price Function                                              |
//******************************************************************************

double FindLastSellPrice(int Magics) {

   double ord_open_price;
   int ord_ticket;
   double buffers = 0;
   int ticket_compair = -1;

   for (int cnt = 0; cnt < OrdersTotal(); cnt++) {

      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if (OrderSymbol() != Symbol() || OrderMagicNumber() != Magics) continue;

      if (OrderSymbol() == Symbol() && OrderMagicNumber() == Magics && OrderType() == OP_SELL) {

         ord_ticket = OrderTicket();
         if (ord_ticket > ticket_compair) {
            ord_open_price = OrderOpenPrice();
            buffers = ord_open_price;
            ticket_compair = ord_ticket;
         }
      }
   }
   return (ord_open_price);
}

//******************************************************************************
//| Day/Time Filter Function                                                   |
//******************************************************************************

  bool DayTimeFilter(int Dates, int start_time, int finish_time) {   

      int start_minute = 0;      
      int finish_minute = 0;
      int Current_Time = TimeHour(TimeCurrent());
      int Current_Minute = TimeMinute(TimeCurrent());
      
      if (start_time==24) start_time = 0; 
      if (finish_time==24) finish_time = 0; 
      if (finish_time>24) {
          finish_time = 23; 
          finish_minute = 59;
          }
      if (Current_Time==24) Current_Time = 0;

      if (!TimeFilter) return(true) ;     
      else      
      if ( TimeFilter && DayOfWeek() == Dates && start_time < finish_time )  {
         if ( (Current_Time >= start_time && Current_Minute >= start_minute) && (Current_Time <= finish_time && Current_Minute <= finish_minute) ) return(true) ;
         else return(false);
      }
      
      if ( TimeFilter && DayOfWeek() == Dates && start_time > finish_time )  {
         if ( (Current_Time >= start_time && Current_Minute >= start_minute) || (Current_Time <= finish_time &&  Current_Minute <= finish_minute) ) return(true) ;
         else return(false);
      } 


//******************************************************************************

  bool DayFilter() {
  
  if (!DateFilter) return(true) ;     
  else      
  if ((MON && DayTimeFilter(1, mon_start_time, mon_finish_time)) || (TUE && DayTimeFilter(2, tue_start_time, tue_finish_time)) || (WED && DayTimeFilter(3, wed_start_time, wed_finish_time)) || (THU && DayTimeFilter(4, thu_start_time, thu_finish_time)) || (FRI && DayTimeFilter(5, fri_start_time, fri_finish_time))) return(true) ;
  else return(false);
  
  }
  
//******************************************************************************
//| Money Management Function                                                  |
//******************************************************************************
// Money Management 설정 0:FixLot,1:Percent,2:Conservative,3:Aggresive 

double MoneyManagement(int DMM, double Percentage) { 

  double DynMM = 0.1;
  double risk = 0.01;
  int mmdigit, adjustlot;

  if(lotstep==0.1) mmdigit = 1;
  else if(lotstep==0.01) mmdigit = 2;
      
  switch(DMM) {   //switch
   case 0 : return(FixLot);
   break;

   case 1 : 
      DynMM = (Percentage * AccountFreeMargin() / 100000);        
      DynMM =  NormalizeDouble(DynMM,mmdigit);
      if (DynMM > maxlot) return(maxlot);
      else if (DynMM < minlot) return(minlot);
      else return(DynMM);   
   break;

   case 2 : 
      if(accfree<10000){adjustlot=1000;}
      if(accfree<20000 && accfree>=10000){adjustlot=900;}
      if(accfree<30000 && accfree>=20000){adjustlot=800;}
      if(accfree<40000 && accfree>=30000){adjustlot=700;}
      if(accfree<50000 && accfree>=40000){adjustlot=600;}
      if(accfree<60000 && accfree>=50000){adjustlot=500;}
      if(accfree<70000 && accfree>=60000){adjustlot=400;}
      if(accfree<80000 && accfree>=70000){adjustlot=300;}
      if(accfree<90000 && accfree>=80000){adjustlot=200;} 
      if(accfree>=90000){adjustlot=100;}

      DynMM = NormalizeDouble(accfree * risk / adjustlot , mmdigit);
      if (DynMM > maxlot) return(maxlot);
      else if (DynMM < minlot) return(minlot);
      else return(DynMM); 
   break;

   case 3 : 
      if(accfree<10000){adjustlot=500;}
      if(accfree<20000 && accfree>=10000){adjustlot=400;}
      if(accfree<30000 && accfree>=20000){adjustlot=300;}
      if(accfree<40000 && accfree>=30000){adjustlot=200;}
      if(accfree<50000 && accfree>=40000){adjustlot=100;}
      if(accfree<60000 && accfree>=50000){adjustlot=50;}
      if(accfree<70000 && accfree>=60000){adjustlot=40;}
      if(accfree<80000 && accfree>=70000){adjustlot=30;}
      if(accfree<90000 && accfree>=80000){adjustlot=20;} 
      if(accfree>=90000){adjustlot=10;}

      DynMM = NormalizeDouble(accfree * risk / adjustlot , mmdigit);
      if (DynMM > maxlot) return(maxlot);
      else if (DynMM < minlot) return(minlot);
      else return(DynMM); 
      
   } //switch
 }

//******************************************************************************
//| Strategy1 Buy Function                                                     |
//******************************************************************************

bool ST1Buy() { 
  bool BuyCondition = FALSE;
  bool CommonCon1 = FALSE;  
  bool BuyCon1 = FALSE;
  bool BuyCon2 = FALSE;
  bool BuyCon3 = FALSE;  

   double LastClose01 = iClose(BaseSymbol, TF01, Shift01);     // 이전 종가
   double MA_LongTarget01 = iMA(BaseSymbol, TF01, MA1_Period01, 0, MODE_SMMA, PRICE_HIGH, Shift01);
   double Stochastic_Con01 = iStochastic(BaseSymbol, TF01, Sto_KPeriod01, Sto_DPeriod01, Sto_Slowing01, MODE_SMA, 0, MODE_MAIN, Shift01);
   double ATR_Con = iATR(BaseSymbol, TF01, ATR_Period01, Shift01);
      
  if( ATR_Con > ATR_Value*mypoints*sympoints && Correlation(BaseSymbol,EntrySymbol,CorPeriod) > TargetCor ) CommonCon1 = TRUE;
  else CommonCon1 = FALSE;
  
  if( LastClose01 - MA_LongTarget01 > MA1_BuyGapValue*mypoints*sympoints ) BuyCon1 = TRUE;
  else BuyCon1 = FALSE;
  
  if( ask00 - LastClose01 <= LastMargin*mypoints*sympoints ) BuyCon2 = TRUE;
  else BuyCon2 = FALSE;
  
   if (Stochastic_Con01 < S1StoTaget) BuyCon3 = TRUE;
   else BuyCon3 = FALSE;
  
  if(CommonCon1 && BuyCon1 && BuyCon2 && BuyCon3) BuyCondition = TRUE;
  else BuyCondition = FALSE;

  return(BuyCondition);
}  

//******************************************************************************
//| Strategy1 Sell Function                                                    |
//******************************************************************************
  
bool ST1Sell() {   
  bool SellCondition = FALSE;
  bool CommonCon1 = FALSE;   
  bool SellCon1 = FALSE;
  bool SellCon2 = FALSE;
  bool SellCon3 = FALSE;  

   double LastClose01 = iClose(BaseSymbol, TF01, Shift01);     // 이전 종가
   double Stochastic_Con01 = iStochastic(BaseSymbol, TF01, Sto_KPeriod01, Sto_DPeriod01, Sto_Slowing01, MODE_SMA, 0, MODE_MAIN, Shift01);
   double ATR_Con = iATR(BaseSymbol, TF01, ATR_Period01, Shift01);
   double MA_LongTarget02 = iMA(BaseSymbol, TF01, MA1_Period01, 0, MODE_SMMA, PRICE_LOW, Shift01);

  if( ATR_Con > ATR_Value*mypoints*sympoints && Correlation(BaseSymbol,EntrySymbol,CorPeriod) > TargetCor ) CommonCon1 = TRUE;
  else CommonCon1 = FALSE;

  if( MA_LongTarget02-LastClose01 > MA1_SellGapValue*mypoints*sympoints ) SellCon1 = TRUE;
  else SellCon1 = FALSE;

  if( bid00-LastClose01 >= -LastMargin*mypoints*sympoints ) SellCon2 = TRUE;
  else SellCon2 = FALSE;

   if (Stochastic_Con01 > 100-S1StoTaget) SellCon3 = TRUE;
   else SellCon3 = FALSE;

  if(CommonCon1 && SellCon1 && SellCon2 && SellCon3) SellCondition = TRUE;
  else SellCondition = FALSE;

  return(SellCondition);


//******************************************************************************
//| Strategy2 Buy Function                                                     |
//******************************************************************************

bool ST2Buy() { 
  bool BuyCondition = FALSE;
  bool CommonCon1 = FALSE;  
  bool BuyCon1 = FALSE;
  bool BuyCon2 = FALSE;
  bool BuyCon3 = FALSE;  

   double LastClose01 = iClose(BaseSymbol, TF01, Shift01);     // 이전 종가
   double MA_LongTarget01 = iMA(BaseSymbol, TF01, MA2_Period01, 0, MODE_SMMA, PRICE_HIGH, Shift01);
   double Stochastic_Con01 = iStochastic(BaseSymbol, TF01, Sto_KPeriod01, Sto_DPeriod01, Sto_Slowing01, MODE_SMA, 0, MODE_MAIN, Shift01);
   double ATR_Con = iATR(BaseSymbol, TF01, ATR_Period01, Shift01);
      
  if( ATR_Con > ATR_Value*mypoints*sympoints && Correlation(BaseSymbol,EntrySymbol,CorPeriod) > TargetCor ) CommonCon1 = TRUE;
  else CommonCon1 = FALSE;
  
  if( LastClose01 - MA_LongTarget01 > MA2_BuyGapValue*mypoints*sympoints ) BuyCon1 = TRUE;
  else BuyCon1 = FALSE;
  
  if( ask00 - LastClose01 <= LastMargin*mypoints*sympoints ) BuyCon2 = TRUE;
  else BuyCon2 = FALSE;
  
   if (Stochastic_Con01 < S2StoTaget) BuyCon3 = TRUE;
   else BuyCon3 = FALSE;
  
  if(CommonCon1 && BuyCon1 && BuyCon2 && BuyCon3) BuyCondition = TRUE;
  else BuyCondition = FALSE;

  return(BuyCondition);
}  

//******************************************************************************
//| Strategy2 Sell Function                                                    |
//******************************************************************************
  
bool ST2Sell() {   
  bool SellCondition = FALSE;
  bool CommonCon1 = FALSE;   
  bool SellCon1 = FALSE;
  bool SellCon2 = FALSE;
  bool SellCon3 = FALSE;  

   double LastClose01 = iClose(BaseSymbol, TF01, Shift01);     // 이전 종가
   double Stochastic_Con01 = iStochastic(BaseSymbol, TF01, Sto_KPeriod01, Sto_DPeriod01, Sto_Slowing01, MODE_SMA, 0, MODE_MAIN, Shift01);
   double ATR_Con = iATR(BaseSymbol, TF01, ATR_Period01, Shift01);
   double MA_LongTarget02 = iMA(BaseSymbol, TF01, MA2_Period01, 0, MODE_SMMA, PRICE_LOW, Shift01);

  if( ATR_Con > ATR_Value*mypoints*sympoints && Correlation(BaseSymbol,EntrySymbol,CorPeriod) > TargetCor ) CommonCon1 = TRUE;
  else CommonCon1 = FALSE;

  if( MA_LongTarget02-LastClose01 > MA2_SellGapValue*mypoints*sympoints ) SellCon1 = TRUE;
  else SellCon1 = FALSE;

  if( bid00-LastClose01 >= -LastMargin*mypoints*sympoints ) SellCon2 = TRUE;
  else SellCon2 = FALSE;

   if (Stochastic_Con01 > 100-S2StoTaget) SellCon3 = TRUE;
   else SellCon3 = FALSE;

  if(CommonCon1 && SellCon1 && SellCon2 && SellCon3) SellCondition = TRUE;
  else SellCondition = FALSE;

  return(SellCondition);


//******************************************************************************
//| Strategy3 Buy Function                                                     |
//******************************************************************************

bool ST3Buy() { 
  bool BuyCondition = FALSE;
  bool CommonCon1 = FALSE;  
  bool BuyCon1 = FALSE;
  bool BuyCon2 = FALSE;
  bool BuyCon3 = FALSE;  

   double LastClose01 = iClose(BaseSymbol, TF01, Shift01);     // 이전 종가
   double MA_LongTarget01 = iMA(BaseSymbol, TF01, MA3_Period01, 0, MODE_SMMA, PRICE_HIGH, Shift01);
   double CCI_Con01 = iCCI(BaseSymbol, TF01, CCI_Period01, PRICE_TYPICAL, Shift01);
   double ATR_Con = iATR(BaseSymbol, TF01, ATR_Period01, Shift01);
      
  if( ATR_Con > ATR_Value*mypoints*sympoints && Correlation(BaseSymbol,EntrySymbol,CorPeriod) > TargetCor ) CommonCon1 = TRUE;
  else CommonCon1 = FALSE;
  
  if( LastClose01 - MA_LongTarget01 > MA3_BuyGapValue*mypoints*sympoints ) BuyCon1 = TRUE;
  else BuyCon1 = FALSE;
  
  if( ask00 - LastClose01 <= LastMargin*mypoints*sympoints ) BuyCon2 = TRUE;
  else BuyCon2 = FALSE;
  
  if (CCI_Con01 < -CCI_Limit01) BuyCon3 = TRUE;
  else BuyCon3 = FALSE;
  
  if(CommonCon1 && BuyCon1 && BuyCon2 && BuyCon3) BuyCondition = TRUE;
  else BuyCondition = FALSE;

  return(BuyCondition);
}  

//******************************************************************************
//| Strategy3 Sell Function                                                    |
//******************************************************************************
  
bool ST3Sell() {   
  bool SellCondition = FALSE;
  bool CommonCon1 = FALSE;   
  bool SellCon1 = FALSE;
  bool SellCon2 = FALSE;
  bool SellCon3 = FALSE;  

   double LastClose01 = iClose(BaseSymbol, TF01, Shift01);     // 이전 종가
   double MA_LongTarget02 = iMA(BaseSymbol, TF01, MA3_Period01, 0, MODE_SMMA, PRICE_LOW, Shift01);   
   double CCI_Con01 = iCCI(BaseSymbol, TF01, CCI_Period01, PRICE_TYPICAL, Shift01);
   double ATR_Con = iATR(BaseSymbol, TF01, ATR_Period01, Shift01);

  if( ATR_Con > ATR_Value*mypoints*sympoints && Correlation(BaseSymbol,EntrySymbol,CorPeriod) > TargetCor ) CommonCon1 = TRUE;
  else CommonCon1 = FALSE;

  if( MA_LongTarget02-LastClose01 > MA3_SellGapValue*mypoints*sympoints ) SellCon1 = TRUE;
  else SellCon1 = FALSE;

  if( bid00-LastClose01 >= -LastMargin*mypoints*sympoints ) SellCon2 = TRUE;
  else SellCon2 = FALSE;

  if (CCI_Con01 > CCI_Limit01) SellCon3 = TRUE;
  else SellCon3 = FALSE;

  if(CommonCon1 && SellCon1 && SellCon2 && SellCon3) SellCondition = TRUE;
  else SellCondition = FALSE;

  return(SellCondition);


//******************************************************************************
//| Strategy4 Buy Function                                                     |
//******************************************************************************

bool ST4Buy() { 
  bool BuyCondition = FALSE;
  bool CommonCon1 = FALSE;  
  bool BuyCon1 = FALSE;
  bool BuyCon2 = FALSE;
  bool BuyCon3 = FALSE;  

   double LastClose01 = iClose(BaseSymbol, TF01, Shift01);     // 이전 종가
   double MA_LongTarget01 = iMA(BaseSymbol, TF01, MA4_Period01, 0, MODE_SMMA, PRICE_HIGH, Shift01);
   double WPR_Value01 = iWPR(BaseSymbol,TF01,WPR_Period01,Shift01); 
   double WPR_Value02 = iWPR(BaseSymbol,TF01,WPR_Period02,Shift01); 
   double ATR_Con = iATR(BaseSymbol, TF01, ATR_Period01, Shift01);
      
  if( ATR_Con > ATR_Value*mypoints*sympoints && Correlation(BaseSymbol,EntrySymbol,CorPeriod) > TargetCor ) CommonCon1 = TRUE;
  else CommonCon1 = FALSE;
  
  if( LastClose01 - MA_LongTarget01 > MA4_BuyGapValue*mypoints*sympoints ) BuyCon1 = TRUE;
  else BuyCon1 = FALSE;
  
  if( ask00 - LastClose01 <= LastMargin*mypoints*sympoints ) BuyCon2 = TRUE;
  else BuyCon2 = FALSE;
  
  if (WPR_Value01 < -100 + ExtraWPR1 || WPR_Value02 < -100 + ExtraWPR2) BuyCon3 = TRUE;
  else BuyCon3 = FALSE;
  
  if(CommonCon1 && BuyCon1 && BuyCon2 && BuyCon3) BuyCondition = TRUE;
  else BuyCondition = FALSE;

  return(BuyCondition);
}  

//******************************************************************************
//| Strategy4 Sell Function                                                    |
//******************************************************************************
  
bool ST4Sell() {   
  bool SellCondition = FALSE;
  bool CommonCon1 = FALSE;   
  bool SellCon1 = FALSE;
  bool SellCon2 = FALSE;
  bool SellCon3 = FALSE;  

   double LastClose01 = iClose(BaseSymbol, TF01, Shift01);     // 이전 종가
   double MA_LongTarget02 = iMA(BaseSymbol, TF01, MA4_Period01, 0, MODE_SMMA, PRICE_LOW, Shift01);   
   double WPR_Value01 = iWPR(BaseSymbol,TF01,WPR_Period01,Shift01); 
   double WPR_Value02 = iWPR(BaseSymbol,TF01,WPR_Period02,Shift01); 
   double ATR_Con = iATR(BaseSymbol, TF01, ATR_Period01, Shift01);

  if( ATR_Con > ATR_Value*mypoints*sympoints && Correlation(BaseSymbol,EntrySymbol,CorPeriod) > TargetCor ) CommonCon1 = TRUE;
  else CommonCon1 = FALSE;

  if( MA_LongTarget02-LastClose01 > MA4_SellGapValue*mypoints*sympoints ) SellCon1 = TRUE;
  else SellCon1 = FALSE;

  if( bid00-LastClose01 >= -LastMargin*mypoints*sympoints ) SellCon2 = TRUE;
  else SellCon2 = FALSE;

  if (WPR_Value01 > -ExtraWPR1 || WPR_Value02 > -ExtraWPR2) SellCon3 = TRUE;
  else SellCon3 = FALSE;

  if(CommonCon1 && SellCon1 && SellCon2 && SellCon3) SellCondition = TRUE;
  else SellCondition = FALSE;

  return(SellCondition);
}

//******************************************************************************
//| Close Buy Condition Function                                               |
//******************************************************************************

bool CloseBuyCondition(int magic, int MinProfit, int PriceTarget)  {  // 0

  bool CloseBuy = FALSE; 
  bool CloseBuyCon01 = FALSE;
  bool CloseBuyCon02 = FALSE;

   double Stochastic_CloseCon01 = iStochastic(NULL, TF01, Sto_KPeriod01, Sto_DPeriod01, Sto_Slowing01, MODE_SMA, 0, MODE_SIGNAL, Shift01);  
   double LastClose01 = iClose(NULL, TF01, Shift01);
   double Close_NowOpen = iOpen(NULL, NowTF01, Shift01);
   double Close_NowClose = iClose(NULL, NowTF01, Shift01);
   double StopPoint = NormalizeDouble(MinProfit * mypoint * sympoint, mydigit);   
   double ClosePricePoint = NormalizeDouble(PriceTarget*mypoint*sympoint, mydigit);

//******************************************************************************
// CloseBuy Condition

   if (bid00 - FindLastBuyPrice(magic) >= StopPoint && LastClose01 - bid00 <= LastMargin*mypoint*sympoint && Stochastic_CloseCon01 > StoCloseBuyTarget) CloseBuyCon01 = TRUE;
   else CloseBuyCon01 = FALSE;
   if (Close_NowOpen > Close_NowClose && bid00 - FindLastBuyPrice(magic) >= ClosePricePoint) CloseBuyCon02 = TRUE;
   else CloseBuyCon02 = FALSE;
   
   if (CloseBuyCon01 == TRUE || CloseBuyCon02 == TRUE) CloseBuy = TRUE;
   else CloseBuy = FALSE;

  return(CloseBuy);
}  // 0

//******************************************************************************
//| Close Sell Condition Function                                              |
//******************************************************************************

bool CloseSellCondition(int magic, int MinProfit, int PriceTarget)  {  // 0

  bool CloseSell = FALSE; 
  bool CloseSellCon01 = FALSE;
  bool CloseSellCon02 = FALSE;

   double Stochastic_CloseCon01 = iStochastic(NULL, TF01, Sto_KPeriod01, Sto_DPeriod01, Sto_Slowing01, MODE_SMA, 0, MODE_SIGNAL, Shift01);  
   double LastClose01 = iClose(NULL, TF01, Shift01);
   double Close_NowOpen = iOpen(NULL, NowTF01, Shift01);
   double Close_NowClose = iClose(NULL, NowTF01, Shift01);
   double StopPoint = NormalizeDouble(MinProfit * mypoint * sympoint, mydigit);   
   double ClosePricePoint = NormalizeDouble(PriceTarget*mypoint*sympoint, mydigit);

//******************************************************************************
// CloseSell Condition
     
   if (FindLastSellPrice(magic) - ask00 >= StopPoint && LastClose01 - ask00 >= -LastMargin*mypoint*sympoint && Stochastic_CloseCon01 < StoCloseSellTarget) CloseSellCon01 = TRUE;
   else CloseSellCon01 = FALSE;
   if (Close_NowOpen < Close_NowClose && FindLastSellPrice(magic) - ask00 >= ClosePricePoint) CloseSellCon02 = TRUE;
   else CloseSellCon02 = FALSE;
   
   if (CloseSellCon01 == TRUE || CloseSellCon02 == TRUE) CloseSell = TRUE;
   else CloseSell = FALSE;

  return(CloseSell);
}  // 0

//******************************************************************************
//| CORRELATION : Calculate the correlation of the 2 pairs                     |
//******************************************************************************

double Correlation(string Base,string Hedge,int Periods) {

  double BaseCur, HedgeCur;

  double MultiPlyCur=0;
  double BasePow=0;
  double HedgePow=0;

   for(int i=Periods-1 ;i >=0 ;i--) {
      BaseCur = iClose(Base,1440,i)-iMA(Base,1440,Periods,0,MODE_SMA,PRICE_CLOSE,i);
      HedgeCur = iClose(Hedge,1440,i)-iMA(Hedge,1440,Periods,0,MODE_SMA,PRICE_CLOSE,i);

      MultiPlyCur += BaseCur * HedgeCur;
      BasePow += MathPow(BaseCur,2);
      HedgePow += MathPow(HedgeCur,2);
     }

   if(BasePow*HedgePow > 0) return(MathAbs(MultiPlyCur/MathSqrt(BasePow*HedgePow)));

}

+ Recent posts