15분봉을 타겟으로 적용하며, EURUSD, GBPUSD, USDJPY, EURGBP, AUDUSD, USDCAD 등의 통화를 대상으로 이동평균과 Stochastic, CCI 등의 지표를 통해 매매를 하도록 개발하였다.
//******************************************************************************
//| YS_Sigma_V0.3 |
//| Copyright @ 2012 Gguri FX LAB |
//******************************************************************************
/*
Time Frame : M15
Pairs : EURUSD, GBPUSD, USDJPY, EURGBP, AUDUSD, USDCAD 등(브로커별로 확인요망)
Based Indicator : MA, Stochastic, CCI Indicator
Start Date : 2012-08-27
Logic : Buy, Sell 각각에 대하여 MA, Stochastic, CCI조건적용 및 ATR필터 적용
//******************************************************************************
//| Version History |
//******************************************************************************
Version 0.1
- Day Filter수정
Version 0.2
- Money Management 기능추가
- Type별 매매건수 < MaxTrades
Version 0.3
- Additional 기능 추가
*/
//******************************************************************************
//| 상수설정 |
//******************************************************************************
#define EA_NAME "YS_Sigma_V0.3"
#define Copyrights " "
#define Create_Date "2012-08-27"
//******************************************************************************
//| Import Library |
//******************************************************************************
#import "stdlib.ex4"
string ErrorDescription(int a0);
//******************************************************************************
//| 공통 변수 설정 |
//******************************************************************************
extern string order_set_string = "Order&Close Settings";
// 주문관련 변수설정
extern bool ECN = TRUE; // ECN Broker 주문처리 가능여부
extern double FixLot=0.1 ; // 진입 랏사이즈 설정
extern double AddLotMultiplier = 2; // Additional Lot Multiplier
extern double slippage = 3.0; // 슬리피지 허용 변수
extern int XSL1 = 120; // StopLoss
extern int XTP1 = 40; // TakeProfit
extern int AddLossPip = 5; // Additional Entry Loss Pips
// Trailing Stop 관련 설정
extern double TrailingStop1 = 20.0; // Trailing Stop 설정시 > 0
extern double TrailingGap1 = 15.0; // Trailing Stop 설정시 가격과의 Gap
extern double BreakEven1 = 12.0; // Break Even 설정시 > 0
extern double BreakPoint1 = 3.0; // Break Even 설정시 손절치(본전 + 손절치)
// 일괄청산관련 설정
extern double StopOutBalance = 500; // 모든 거래 종료 잔고 설정
extern bool CloseAllFilter = FALSE; // CloseAll Enabled
extern bool CloseFilter = TRUE; // 청산시 지표사용
extern int All_SL = 200; // CloseAll StopLoss
extern int All_TP = 60; // CloseAll TakeProfit
// Money Management 설정
extern string MM_set_string = "MM = 0:FixLot,1:Percent,2:Conservative,3:Aggresive";
extern int DynamicMM = 0; // Money Management 설정 0:FixLot,1:Percent,2:Conservative,3:Aggresive
extern double RiskPercent = 5.0; // MM = 1일때 0보다 큰 숫자 설정
// 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시 사용 소리파일
extern bool SimpleScreen = TRUE; // 화면표시 단순화
//******************************************************************************
//| 제한조건 관련 설정(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 MaxTrades = 1; // 최대 허용 거래수
extern int MinBars = 100; // 최소 다운로드 Bar의 수
extern bool DateFilter = FALSE; // 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 = 9; // 월요일 거래시작시간
extern int mon_finish_time = 25; // 월요일 거래종료시간
extern int tue_start_time = 9; // 화요일 거래시작시간
extern int tue_finish_time = 25; // 화요일 거래종료시간
extern int wed_start_time = 9; // 수요일 거래시작시간
extern int wed_finish_time = 25; // 수요일 거래종료시간
extern int thu_start_time = 9; // 목요일 거래시작시간
extern int thu_finish_time = 25; // 목요일 거래종료시간
extern int fri_start_time = 9; // 금요일 거래시작시간
extern int fri_finish_time = 19; // 금요일 거래종료시간
//******************************************************************************
//| Entry Logic 관련 변수 설정 |
//******************************************************************************
extern string ref_entry_string = "Entry Settings";
extern int TimeFrame = 15;
extern int PriceTimeFrame = 1;
extern int ShiftTime = 1;
extern int iMA_PeriodLONG = 55;
extern int iMA_ShiftTime = 0;
extern int iMA_LONG_Open_a = 18;
extern int iMA_LONG_Open_b = 39;
extern int iMA_PeriodShort = 55;
extern int iMA_Short_Open_a = 15;
extern int iMA_Short_Open_b = 39;
extern int iCCI_PeriodLONG = 18;
extern int iCCI_PeriodShort = 18;
extern double iCCI_OpenFilter = 150.0;
extern bool ATRFilter = TRUE;
int ATR_Buy_Period = 14;
int ATR_Sell_Period = 14;
int iStoDperiod = 1;
int iStoSlowingValue = 1;
extern int iWPR_PeriodLONG = 11;
extern int iWPR_PeriodShort = 11;
extern int iWPR_LONG_Open_a = 1;
extern int iWPR_LONG_Open_b = 5;
extern int iWPR_Short_Open_a = 1;
extern int iWPR_Short_Open_b = 5;
extern int iWPR_Filter_Close = 90;
extern int FilterATR = 6;
extern int Price_Filter_Close = 14;
extern int MinProfit = 5;
//******************************************************************************
//| 기타 내생 변수 설정 |
//******************************************************************************
string Commentary = EA_NAME; // Entry 주문시 비고
string Com1 = "Initial"; // Initial Entry 주문시 비고
string Com2 = "Additional"; // Additional Entry 주문시 비고
int mypoint; // 4 digit, 5digit broker에 대한 point 설정변수
string NowSym, StartDay; // EA 시작일 및 심볼 조정변수
int error_code; // 에러코드
int magic1, magic2; // magic number global variable 설정
datetime S1Time1,S1Time2; // Strategy1 NewBar 시간변수
datetime S2Time1,S2Time2; // Strategy2 NewBar 시간변수
// MarketInfo 정보를 받는 변수
string broker,servername,mytime,ScreenStr;
double equity,reqmargin,stopout,minlot,maxlot,lotstep;
double accfree,sympoint,ask00,bid00,spread,tickvalue,ticksize;
int leverage,mydigit,stoplevel,freeze;
//******************************************************************************
//| 초기화 |
//******************************************************************************
int init() { // 초기화 시작
/*
// Period Protection
if(Period() != PERIOD_M5) {
Alert("5분봉 차트에 붙이셔야 합니다.");
return(0);
}
*/
// 거래 가능여부 확인
if(IsTradeAllowed()) {
Print("거래 가능합니다!");
}
// Money Management 정확한 설정확인
if(DynamicMM == 1 && RiskPercent == 0) {
Alert("RiskPercent값을 0 이상으로 설정하세요.");
return(0);
}
if(DynamicMM > 3) {
Alert("DynamicMM값을 3 이하값으로 설정하세요.");
return(0);
}
// 데이타 다운로드 미비에 의한 오류계산 방지 로직
if(!DataFilter()) {
Print ("아! Bar가 아직 모자라!ㅠㅠ..");
return(0);
}
// EA 시작일 설정
StartDay = TimeToStr(TimeCurrent(),TIME_DATE);
// 통화별 매직넘버 가져오기
getmagic();
magic2 = magic1+2000;
// 5 digit broker adjustment
if(MarketInfo(Symbol(), MODE_DIGITS)==3 || MarketInfo(Symbol(), MODE_DIGITS)==5) {
mypoint = 10;
}
else
{
mypoint = 1;
}
} // 초기화 종료
//******************************************************************************
//| 종료시 설정 |
//******************************************************************************
int deinit() {
return(0);
}
//******************************************************************************
//| EA Start |
//******************************************************************************
int start() { // EA 시작
//******************************************************************************
// Error 검출후 메세지 출력
// Server와 연결이 안된 경우
if(!IsConnected()) {
Print("연결해주세요!");
return(0);
}
// EA 거래를 막아놓은 경우
if(!IsTesting()) {
if(!IsDllsAllowed() || !IsExpertEnabled()) {
Print("DLL 사용할 수 있게 옵션에서 풀어주세요. 혹은 EA아이콘 확인요망!");
return(0);
}
}
// 데이타 다운로드 미비에 의한 오류계산 방지 로직
if(!DataFilter()) {
Print ("아! Bar가 아직 모자라!ㅠㅠ..");
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);
sympoint = MarketInfo(Symbol(),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,TrailingGap1);
if(BreakEven1>0) MoveBreakEven(magic1,BreakEven1,BreakPoint1);
//******************************************************************************
//| Date/Time Filter |
//******************************************************************************
// Day/Time Filter충족여부 검토
bool DateEnabled = FALSE;
if (DayFilter()) DateEnabled = TRUE;
else DateEnabled = FALSE;
//******************************************************************************
// Spread 조건 충족여부 검토
bool SpreadEnabled = TRUE;
if (TradeEnable()==FALSE) {
Print ("아! Spread가 너무 쎄!ㅠㅠ..");
SpreadEnabled = FALSE;
}
else SpreadEnabled = TRUE;
//******************************************************************************
// 잔고가 일정액 이하인 경우 EA 진입금지
bool EnoughMoney = TRUE;
if(AccountFreeMargin()<(1000*FixLot)) {
Print("돈이 없어. 현잔고 = ", accfree);
EnoughMoney = FALSE;
}
else EnoughMoney = TRUE;
//******************************************************************************
// Spread조건 및 Day/Time Filter충족여부 검토
bool EntryEnabled = FALSE;
if (DateEnabled && SpreadEnabled && EnoughMoney) EntryEnabled = TRUE;
else EntryEnabled = FALSE;
//******************************************************************************
//| Order 주문처리 Logic |
//******************************************************************************
bool Entry_1 = FALSE;
int ticketbuy1, ticketsell1;
if(EntryEnabled) 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
double orderlots = NormalizeDouble(MoneyManagement(),2);
// Buy Order
if(OrderTotalControl) {
if(Entry_1 && TotalOrders(magic1) < MaxTrades && S1NewBarBuy) {
if(BuyCondition()) {
ticketbuy1 = OpenOrder(Symbol(),OP_BUY,orderlots,slippage,XSL1,XTP1,Com1,magic1);
}
}
}
else
if(!OrderTotalControl) {
if(Entry_1 && TotalBuyOrders(magic1) < MaxTrades && S1NewBarBuy) {
if(BuyCondition()) {
ticketbuy1 = OpenOrder(Symbol(),OP_BUY,orderlots,slippage,XSL1,XTP1,Com1,magic1);
}
}
}
// Sell Order
if(OrderTotalControl) {
if(Entry_1 && TotalOrders(magic1) < MaxTrades && S1NewBarSell) {
if(SellCondition()) {
ticketsell1 = OpenOrder(Symbol(),OP_SELL,orderlots,slippage,XSL1,XTP1,Com1,magic1);
}
}
}
else
if(!OrderTotalControl) {
if(Entry_1 && TotalSellOrders(magic1) < MaxTrades && S1NewBarSell) {
if(SellCondition()) {
ticketsell1 = OpenOrder(Symbol(),OP_SELL,orderlots,slippage,XSL1,XTP1,Com1,magic1);
}
}
}
//******************************************************************************
//| Strategy 2 Buy/Sell Condition Function |
//******************************************************************************
//******************************************************************************
// Buy/Sell Breakout
bool Buy2Con = FALSE;
bool Sell2Con = FALSE;
if ( TotalBuyOrders(magic1)>0 && BuyCondition() && ask00 < FindLastBuyPrice(magic1) - AddLossPip * mypoint * sympoint ) Buy2Con = TRUE;
else Buy2Con = FALSE;
if ( TotalSellOrders(magic1)>0 && SellCondition() && bid00 > FindLastSellPrice(magic1) + AddLossPip * mypoint * sympoint ) Sell2Con = TRUE;
else Sell2Con = FALSE;
//******************************************************************************
// Strategy 2 Order
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
double orderlot2 = NormalizeDouble(MoneyManagement()*AddLotMultiplier,2);
int ticketbuy2, ticketsell2;
// Buy Order
if(OrderTotalControl) {
if(Entry_1 && TotalOrders(magic2) < MaxTrades && S2NewBarBuy) {
if(Buy2Con) {
ticketbuy2 = OpenOrder(Symbol(),OP_BUY,orderlot2,slippage,XSL1,XTP1,Com2,magic2);
}
}
}
else
if(!OrderTotalControl) {
if(Entry_1 && TotalBuyOrders(magic2) < MaxTrades && S2NewBarBuy) {
if(Buy2Con) {
ticketbuy2 = OpenOrder(Symbol(),OP_BUY,orderlot2,slippage,XSL1,XTP1,Com2,magic2);
}
}
}
// Sell Order
if(OrderTotalControl) {
if(Entry_1 && TotalOrders(magic2) < MaxTrades && S2NewBarSell) {
if(Sell2Con) {
ticketsell2 = OpenOrder(Symbol(),OP_SELL,orderlot2,slippage,XSL1,XTP1,Com2,magic2);
}
}
}
else
if(!OrderTotalControl) {
if(Entry_1 && TotalSellOrders(magic2) < MaxTrades && S2NewBarSell) {
if(Sell2Con) {
ticketsell2 = OpenOrder(Symbol(),OP_SELL,orderlot2,slippage,XSL1,XTP1,Com2,magic2);
}
}
}
//******************************************************************************
//| Close Condition Function |
//******************************************************************************
//******************************************************************************
// 지표사용시 Close 조건 충족시 청산(전략1 해당)
if(CloseFilter && TotalBuyOrders(magic1)>0) {
if(CloseBuyCondition(magic1)) {
CloseBuyOpens(magic1);
}
}
if(CloseFilter && TotalBuyOrders(magic2)>0) {
if(CloseBuyCondition(magic2)) {
CloseBuyOpens(magic2);
}
}
if(CloseFilter && TotalSellOrders(magic1)>0) {
if(CloseSellCondition(magic1)) {
CloseSellOpens(magic1);
}
}
if(CloseFilter && TotalSellOrders(magic2)>0) {
if(CloseSellCondition(magic2)) {
CloseSellOpens(magic2);
}
}
//******************************************************************************
//| Close All Function |
//******************************************************************************
//******************************************************************************
// 전체수익이나 손실이 설정치 이상인 경우 Close All
bool ProfitAll = FALSE;
double profits = Profit(magic1)+Profit(magic2);
// Close All TP, Sl을 Lot수에 따라 조정
int AllMultiplier = 10;
double All_SLs = NormalizeDouble(AllMultiplier * All_SL * MoneyManagement(),0);
double All_TPs = NormalizeDouble(AllMultiplier * All_TP * MoneyManagement(),0);
if((TotalOrders(magic1)+TotalOrders(magic2) >= 2) && CloseAllFilter && (profits>All_TPs || profits<-All_SLs)) {
if(TotalBuyOrders(magic1)>0) CloseBuyOpens(magic1);
if(TotalSellOrders(magic1)>0) CloseSellOpens(magic1);
if(TotalBuyOrders(magic2)>0) CloseBuyOpens(magic2);
if(TotalSellOrders(magic2)>0) CloseSellOpens(magic2);
}
//******************************************************************************
//| 화면표시 함수 |
//******************************************************************************
// 화면표시 함수처리에 시간이 많이 걸려 BackTest나 최적화작업시 시간이 많이 걸리므로 이 작업시 이전에 Exit
if(IsTesting()) return(0);
// 화면표시 변수 정의
double hprofit = HistoryProfit(magic1)+HistoryProfit(magic2);
int orders = TotalOrders(magic1)+TotalOrders(magic2);
int borders = TotalBuyOrders(magic1)+TotalBuyOrders(magic2);
int sorders = TotalSellOrders(magic1)+TotalSellOrders(magic2);
int hborders = HBuyOrders(magic1)+HBuyOrders(magic2);
int hsorders = HSellOrders(magic1)+HSellOrders(magic2);
int horders = hborders+hsorders;
double hbprofit = HBProfit(magic1)+HBProfit(magic2);
double hsprofit = HSProfit(magic1)+HSProfit(magic2);
string symbolpoint = DoubleToStr(sympoint,Digits);
string strspread = DoubleToStr(spread,Digits);
string maxspread = DoubleToStr(MaxSpreads*mypoint*sympoint,Digits);
bool ATR_Buy = FALSE;
if(iATR(NULL, TimeFrame, ATR_Buy_Period, ShiftTime) > FilterATR * mypoint * sympoint) ATR_Buy = TRUE;
else ATR_Buy = FALSE;
bool Buy1_1 = FALSE;
if(iClose(NULL, TimeFrame, ShiftTime) - iMA(NULL, TimeFrame, iMA_PeriodLONG, iMA_ShiftTime, MODE_SMMA, PRICE_HIGH, ShiftTime) > NormalizeDouble(iMA_LONG_Open_a*mypoint*sympoint, mydigit)) Buy1_1 = TRUE;
else Buy1_1 = FALSE;
bool Buy1_2 = FALSE;
if(iClose(NULL, TimeFrame, ShiftTime) - bid00 >= -(mypoint*sympoint)) Buy1_2 = TRUE;
else Buy1_2 = FALSE;
bool Buy1_3 = FALSE;
if(iWPR_LONG_Open_a > iStochastic(NULL, TimeFrame, iWPR_PeriodLONG, iStoDperiod, iStoSlowingValue, MODE_SMA, 0, MODE_MAIN, ShiftTime)) Buy1_3 = TRUE;
else Buy1_3 = FALSE;
bool Buy2_1 = FALSE;
if(iClose(NULL, TimeFrame, ShiftTime) - iMA(NULL, TimeFrame, iMA_PeriodLONG, iMA_ShiftTime, MODE_SMMA, PRICE_HIGH, ShiftTime) > NormalizeDouble(iMA_LONG_Open_b*mypoint*sympoint, mydigit)) Buy2_1 = TRUE;
else Buy2_1 = FALSE;
bool Buy2_2 = FALSE;
if(iClose(NULL, TimeFrame, ShiftTime) - bid00 >= -(mypoint*sympoint)) Buy2_2 = TRUE;
else Buy2_2 = FALSE;
bool Buy2_3 = FALSE;
if(-iCCI_OpenFilter > iCCI(NULL, TimeFrame, iCCI_PeriodLONG, PRICE_TYPICAL, ShiftTime)) Buy2_3 = TRUE;
else Buy2_3 = FALSE;
bool Buy3_1 = FALSE;
if(iClose(NULL, TimeFrame, ShiftTime) - iMA(NULL, TimeFrame, iMA_PeriodLONG, iMA_ShiftTime, MODE_SMMA, PRICE_HIGH, ShiftTime) > NormalizeDouble(iMA_LONG_Open_b*mypoint*sympoint, mydigit)) Buy3_1 = TRUE;
else Buy3_1 = FALSE;
bool Buy3_2 = FALSE;
if(iClose(NULL, TimeFrame, ShiftTime) - bid00 >= -(mypoint*sympoint)) Buy3_2 = TRUE;
else Buy3_2 = FALSE;
bool Buy3_3 = FALSE;
if(iWPR_LONG_Open_b > iStochastic(NULL, TimeFrame, iWPR_PeriodLONG, iStoDperiod, iStoSlowingValue, MODE_SMA, 0, MODE_MAIN, ShiftTime)) Buy3_3 = TRUE;
else Buy3_3 = FALSE;
bool ATR_Sell = FALSE;
if(iATR(NULL, TimeFrame, ATR_Sell_Period, ShiftTime) > FilterATR * mypoint * sympoint) ATR_Sell = TRUE;
else ATR_Sell = FALSE;
bool Sell1_1 = FALSE;
if(iMA(NULL, TimeFrame, iMA_PeriodShort, iMA_ShiftTime, MODE_SMMA, PRICE_LOW, ShiftTime) - iClose(NULL, TimeFrame, ShiftTime) > NormalizeDouble(iMA_Short_Open_a*mypoint*sympoint, mydigit)) Sell1_1 = TRUE;
else Sell1_1 = FALSE;
bool Sell1_2 = FALSE;
if(iClose(NULL, TimeFrame, ShiftTime) - bid00 <= (mypoint*sympoint)) Sell1_2 = TRUE;
else Sell1_2 = FALSE;
bool Sell1_3 = FALSE;
if(iStochastic(NULL, TimeFrame, iWPR_PeriodShort, iStoDperiod, iStoSlowingValue, MODE_SMA, 0, MODE_MAIN, ShiftTime) > 100 - iWPR_Short_Open_a) Sell1_3 = TRUE;
else Sell1_3 = FALSE;
bool Sell2_1 = FALSE;
if(iMA(NULL, TimeFrame, iMA_PeriodShort, iMA_ShiftTime, MODE_SMMA, PRICE_LOW, ShiftTime) - iClose(NULL, TimeFrame, ShiftTime) > NormalizeDouble(iMA_Short_Open_b*mypoint*sympoint, mydigit)) Sell2_1 = TRUE;
else Sell2_1 = FALSE;
bool Sell2_2 = FALSE;
if(iClose(NULL, TimeFrame, ShiftTime) - bid00 <= (mypoint*sympoint)) Sell2_2 = TRUE;
else Sell2_2 = FALSE;
bool Sell2_3 = FALSE;
if(iCCI(NULL, TimeFrame, iCCI_PeriodShort, PRICE_TYPICAL, ShiftTime) > iCCI_OpenFilter) Sell2_3 = TRUE;
else Sell2_3 = FALSE;
bool Sell3_1 = FALSE;
if(iMA(NULL, TimeFrame, iMA_PeriodShort, iMA_ShiftTime, MODE_SMMA, PRICE_LOW, ShiftTime) - iClose(NULL, TimeFrame, ShiftTime) > NormalizeDouble(iMA_Short_Open_b*mypoint*sympoint, mydigit)) Sell3_1 = TRUE;
else Sell3_1 = FALSE;
bool Sell3_2 = FALSE;
if(iClose(NULL, TimeFrame, ShiftTime) - bid00 <= (mypoint*sympoint)) Sell3_2 = TRUE;
else Sell3_2 = FALSE;
bool Sell3_3 = FALSE;
if(iStochastic(NULL, TimeFrame, iWPR_PeriodShort, iStoDperiod, iStoSlowingValue, MODE_SMA, 0, MODE_MAIN, ShiftTime) > 100 - iWPR_Short_Open_b) Sell3_3 = TRUE;
else Sell3_3 = FALSE;
string ScreenStr;
ScreenStr = StringConcatenate("EA Name : ",EA_NAME," , Copyright : ",Copyrights," , EA제작일_",Create_Date," , 현재시간 : ",mytime," 평가잔액 = $",equity," Leverage_",leverage,":1, 1Lot당 필요증거금 : $",reqmargin)+"\n";
ScreenStr = ScreenStr + StringConcatenate("Broker : ",broker," Server : ",servername," EA시작일_",StartDay," Order Lot_",orderlots," 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," Data_",DataFilter()," Date_",DayFilter())+"\n";
ScreenStr = ScreenStr + "===========================================================================================================" + "\n";
ScreenStr = ScreenStr + StringConcatenate("Filters : Date Filter_",DateFilter," , Time Filter_",TimeFilter," , Close Filter_",CloseFilter," , ATR_Filter_",ATRFilter) + "\n";
ScreenStr = ScreenStr + StringConcatenate(ATR_Buy," ATR_Buy_Filter : ",iATR(NULL, TimeFrame, ATR_Buy_Period, ShiftTime)," > ",FilterATR * mypoint * sympoint) + "\n";
ScreenStr = ScreenStr + StringConcatenate(Buy1_1," Buy 1-1 : BaseClose - MA_Buy_Condition > iMA_Buy01 : ",iClose(NULL, TimeFrame, ShiftTime)," - ",iMA(NULL, TimeFrame, iMA_PeriodLONG, iMA_ShiftTime, MODE_SMMA, PRICE_HIGH, ShiftTime)," > ",NormalizeDouble(iMA_LONG_Open_a*mypoint*sympoint, mydigit))+"\n";
ScreenStr = ScreenStr + StringConcatenate(Buy1_2," Buy 1-2 : BaseClose - Bid >= (-mypoint * sympoint) : ",iClose(NULL, TimeFrame, ShiftTime)," - ",bid00," >= ",-(mypoint*sympoint))+"\n";
ScreenStr = ScreenStr + StringConcatenate(Buy1_3," Buy 1-3 : iWPR_LONG_Open_a > Stochastic_Buy_Condition : ",iWPR_LONG_Open_a," > ",iStochastic(NULL, TimeFrame, iWPR_PeriodLONG, iStoDperiod, iStoSlowingValue, MODE_SMA, 0, MODE_MAIN, ShiftTime))+"\n";
ScreenStr = ScreenStr + StringConcatenate(Buy2_1," Buy 2-1 : BaseClose - MA_Buy_Condition > iMA_Buy02 : ",iClose(NULL, TimeFrame, ShiftTime)," - ",iMA(NULL, TimeFrame, iMA_PeriodLONG, iMA_ShiftTime, MODE_SMMA, PRICE_HIGH, ShiftTime)," > ",NormalizeDouble(iMA_LONG_Open_b*mypoint*sympoint, mydigit))+"\n";
ScreenStr = ScreenStr + StringConcatenate(Buy2_2," Buy 2-2 : BaseClose - Bid >= (-mypoint * sympoint) : ",iClose(NULL, TimeFrame, ShiftTime)," - ",bid00," >= ",-(mypoint*sympoint))+"\n";
ScreenStr = ScreenStr + StringConcatenate(Buy2_3," Buy 2-3 : -iCCI_OpenFilter > CCI_Buy_Condition : ",-iCCI_OpenFilter," > ",iCCI(NULL, TimeFrame, iCCI_PeriodLONG, PRICE_TYPICAL, ShiftTime))+"\n";
ScreenStr = ScreenStr + StringConcatenate(Buy3_1," Buy 3-1 : BaseClose - MA_Buy_Condition > iMA_Buy02 : ",iClose(NULL, TimeFrame, ShiftTime)," - ",iMA(NULL, TimeFrame, iMA_PeriodLONG, iMA_ShiftTime, MODE_SMMA, PRICE_HIGH, ShiftTime)," > ",NormalizeDouble(iMA_LONG_Open_b*mypoint*sympoint, mydigit))+"\n";
ScreenStr = ScreenStr + StringConcatenate(Buy3_2," Buy 3-2 : BaseClose - Bid >= (-mypoint * sympoint) : ",iClose(NULL, TimeFrame, ShiftTime)," - ",bid00," >= ",-(mypoint*sympoint))+"\n";
ScreenStr = ScreenStr + StringConcatenate(Buy3_3," Buy 3-3 : iWPR_LONG_Open_b > Stochastic_Buy_Condition : ",iWPR_LONG_Open_b," > ",iStochastic(NULL, TimeFrame, iWPR_PeriodLONG, iStoDperiod, iStoSlowingValue, MODE_SMA, 0, MODE_MAIN, ShiftTime))+"\n";
ScreenStr = ScreenStr + "==========================================================================" + "\n";
ScreenStr = ScreenStr + StringConcatenate(ATR_Sell," ATR_Sell_Filter : ",iATR(NULL, TimeFrame, ATR_Sell_Period, ShiftTime)," > ",FilterATR * mypoint * sympoint) + "\n";
ScreenStr = ScreenStr + StringConcatenate(Sell1_1," Sell 1-1 : MA_Sell_Condition - BaseClose > iMA_Sell01 : ",iMA(NULL, TimeFrame, iMA_PeriodShort, iMA_ShiftTime, MODE_SMMA, PRICE_LOW, ShiftTime)," - ",iClose(NULL, TimeFrame, ShiftTime)," > ",NormalizeDouble(iMA_Short_Open_a*mypoint*sympoint, mydigit))+"\n";
ScreenStr = ScreenStr + StringConcatenate(Sell1_2," Sell 1-2 : BaseClose - Bid <= (mypoint * sympoint) : ",iClose(NULL, TimeFrame, ShiftTime)," - ",bid00," <= ",(mypoint*sympoint))+"\n";
ScreenStr = ScreenStr + StringConcatenate(Sell1_3," Sell 1-3 : Stochastic_Sell_Condition > iWPR_Short_ReverseA : ",iStochastic(NULL, TimeFrame, iWPR_PeriodShort, iStoDperiod, iStoSlowingValue, MODE_SMA, 0, MODE_MAIN, ShiftTime)," > ",100 - iWPR_Short_Open_a)+"\n";
ScreenStr = ScreenStr + StringConcatenate(Sell2_1," Sell 2-1 : MA_Sell_Condition - BaseClose > iMA_Sell02 : ",iMA(NULL, TimeFrame, iMA_PeriodShort, iMA_ShiftTime, MODE_SMMA, PRICE_LOW, ShiftTime)," - ",iClose(NULL, TimeFrame, ShiftTime)," > ",NormalizeDouble(iMA_Short_Open_b*mypoint*sympoint, mydigit))+"\n";
ScreenStr = ScreenStr + StringConcatenate(Sell2_2," Sell 2-2 : BaseClose - Bid <= (mypoint * sympoint) : ",iClose(NULL, TimeFrame, ShiftTime)," - ",bid00," <= ",(mypoint*sympoint))+"\n";
ScreenStr = ScreenStr + StringConcatenate(Sell2_3," Sell 2-3 : CCI_Sell_Condition > iCCI_OpenFilter : ",iCCI(NULL, TimeFrame, iCCI_PeriodShort, PRICE_TYPICAL, ShiftTime)," > ",iCCI_OpenFilter)+"\n";
ScreenStr = ScreenStr + StringConcatenate(Sell3_1," Sell 3-1 : MA_Sell_Condition - BaseClose > iMA_Sell02 : ",iMA(NULL, TimeFrame, iMA_PeriodShort, iMA_ShiftTime, MODE_SMMA, PRICE_LOW, ShiftTime)," - ",iClose(NULL, TimeFrame, ShiftTime)," > ",NormalizeDouble(iMA_Short_Open_b*mypoint*sympoint, mydigit))+"\n";
ScreenStr = ScreenStr + StringConcatenate(Sell3_2," Sell 3-2 : BaseClose - Bid <= (mypoint * sympoint) : ",iClose(NULL, TimeFrame, ShiftTime)," - ",bid00," <= ",(mypoint*sympoint))+"\n";
ScreenStr = ScreenStr + StringConcatenate(Sell3_3," Sell 3-3 : Stochastic_Sell_Condition > iWPR_Short_ReverseB : ",iStochastic(NULL, TimeFrame, iWPR_PeriodShort, iStoDperiod, iStoSlowingValue, MODE_SMA, 0, MODE_MAIN, ShiftTime)," > ",100 - iWPR_Short_Open_b)+"\n";
ScreenStr = ScreenStr + "==========================================================================" + "\n";
ScreenStr = ScreenStr + StringConcatenate("Init Profits : ",Profit(magic1),", Init Orders : ",TotalOrders(magic1),"건 = Buy ",TotalBuyOrders(magic1),"건 / Sell",TotalSellOrders(magic1),"건") + "\n";
ScreenStr = ScreenStr + StringConcatenate("Add Profits : ",Profit(magic2),", Add Orders : ",TotalOrders(magic2),"건 = Buy ",TotalBuyOrders(magic2),"건 / Sell",TotalSellOrders(magic2),"건") + "\n";
ScreenStr = ScreenStr + StringConcatenate("Total Profits : $",hprofit,", Buy : $",hbprofit,", Sell : $",hsprofit,", Total Orders : ",horders,"건 = Total Buy ",hborders,"건 / Total Sell",hsorders,"건");
Comment(ScreenStr);
return(0);
} // EA 종료
//******************************************************************************
//| Data Filter Function |
//******************************************************************************
// 데이타 다운로드 미비에 의한 오류계산 방지 로직
bool DataFilter() {
if(iBars(Symbol(), 0) < 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);
}
//******************************************************************************
//| 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(),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(),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(),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(),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(),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(),2);
} // 3
} // 2
} // 1
return(Prof);
} // 0
/*
//******************************************************************************
//| Total order Calculate Function(총오더수 계산 함수,과거치 포함) |
//******************************************************************************
int 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
//******************************************************************************
//| Trailing Stop Function |
//******************************************************************************
void MoveTrailingStop(int Magics,double TrailingStop,double TrailingGap) {
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-TrailingGap*mypoint*sympoint,Digits))||(OrderStopLoss()==0)) {
OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(bid00-TrailingGap*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+TrailingGap*mypoint*sympoint,Digits)))||(OrderStopLoss()==0)) {
OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(ask00+TrailingGap*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 = 23480001;
if(NowSym == "GBPUSD") magic1 = 23480002;
if(NowSym == "USDJPY") magic1 = 23480003;
if(NowSym == "AUDUSD") magic1 = 23480004;
if(NowSym == "EURGBP") magic1 = 23480005;
if(NowSym == "USDCAD") magic1 = 23480006;
if(NowSym == "USDCHF") magic1 = 23480007;
if(NowSym == "CHFJPY") magic1 = 23480008;
if(NowSym == "EURJPY") magic1 = 23480009;
if(NowSym == "NZDUSD") magic1 = 23480010;
if(NowSym == "GBPJPY") magic1 = 23480011;
if(NowSym == "EURAUD") magic1 = 23480012;
if(NowSym == "EURCAD") magic1 = 23480013;
if(NowSym == "EURCHF") magic1 = 23480014;
if(NowSym == "CADJPY") magic1 = 23480015;
if(NowSym == "AUDNZD") magic1 = 23480016;
if(NowSym == "AUDCAD") magic1 = 23480017;
if(NowSym == "AUDCHF") magic1 = 23480018;
if(NowSym == "AUDJPY") magic1 = 23480019;
if(NowSym == "GBPAUD") magic1 = 23480020;
if(NowSym == "NZDJPY") magic1 = 23480021;
if(NowSym == "GBPCAD") magic1 = 23480022;
if(NowSym == "NZDCAD") magic1 = 23480023;
if(NowSym == "CADCHF") magic1 = 23480024;
if(NowSym == "GBPNZD") magic1 = 23480025;
if(NowSym == "EURNZD") magic1 = 23480026;
if(NowSym == "NZDCHF") magic1 = 23480027;
if(NowSym == "GBPCHF") magic1 = 23480028;
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() {
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(DynamicMM) { //switch
case 0 : return(FixLot);
break;
case 1 :
DynMM = (RiskPercent * 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
}
//******************************************************************************
//| Buy/Sell Condition Function |
//******************************************************************************
//******************************************************************************
// Buy Condition
bool BuyCondition() {
bool BuyCon = FALSE;
bool BuyCon01 = FALSE;
bool BuyCon02 = FALSE;
bool BuyCon03 = FALSE;
double BaseClose = iClose(NULL, TimeFrame, ShiftTime);
double MA_Buy_Condition = iMA(NULL, TimeFrame, iMA_PeriodLONG, iMA_ShiftTime, MODE_SMMA, PRICE_HIGH, ShiftTime);
double Stochastic_Buy_Condition = iStochastic(NULL, TimeFrame, iWPR_PeriodLONG, iStoDperiod, iStoSlowingValue, MODE_SMA, 0, MODE_MAIN, ShiftTime);
double CCI_Buy_Condition = iCCI(NULL, TimeFrame, iCCI_PeriodLONG, PRICE_TYPICAL, ShiftTime);
double ATR_Buy_Condition = iATR(NULL, TimeFrame, ATR_Buy_Period, ShiftTime);
double iMA_Buy01 = NormalizeDouble(iMA_LONG_Open_a*mypoint*sympoint, mydigit);
double iMA_Buy02 = NormalizeDouble(iMA_LONG_Open_b*mypoint*sympoint, mydigit);
if (ATRFilter && ATR_Buy_Condition <= FilterATR * mypoint * sympoint) return (0);
if (BaseClose - MA_Buy_Condition > iMA_Buy01 && BaseClose - bid00 >= (-mypoint * sympoint) && iWPR_LONG_Open_a > Stochastic_Buy_Condition) BuyCon01 = TRUE;
else BuyCon01 = FALSE;
if (BaseClose - MA_Buy_Condition > iMA_Buy02 && BaseClose - bid00 >= (-mypoint * sympoint) && (-iCCI_OpenFilter) > CCI_Buy_Condition) BuyCon02 = TRUE;
else BuyCon02 = FALSE;
if (BaseClose - MA_Buy_Condition > iMA_Buy02 && BaseClose - bid00 >= (-mypoint * sympoint) && iWPR_LONG_Open_b > Stochastic_Buy_Condition) BuyCon03 = TRUE;
else BuyCon03 = FALSE;
if (BuyCon01 == TRUE || BuyCon02 == TRUE || BuyCon03 == TRUE) BuyCon = TRUE;
else BuyCon = FALSE;
return (BuyCon);
}
//******************************************************************************
// Sell Condition
bool SellCondition() {
bool SellCon = FALSE;
bool SellCon01 = FALSE;
bool SellCon02 = FALSE;
bool SellCon03 = FALSE;
double BaseClose = iClose(NULL, TimeFrame, ShiftTime);
double MA_Sell_Condition = iMA(NULL, TimeFrame, iMA_PeriodShort, iMA_ShiftTime, MODE_SMMA, PRICE_LOW, ShiftTime);
double Stochastic_Sell_Condition = iStochastic(NULL, TimeFrame, iWPR_PeriodShort, iStoDperiod, iStoSlowingValue, MODE_SMA, 0, MODE_MAIN, ShiftTime);
double CCI_Sell_Condition = iCCI(NULL, TimeFrame, iCCI_PeriodShort, PRICE_TYPICAL, ShiftTime);
double ATR_Sell_Condition = iATR(NULL, TimeFrame, ATR_Sell_Period, ShiftTime);
double iMA_Sell01 = NormalizeDouble(iMA_Short_Open_a*mypoint*sympoint, mydigit);
double iMA_Sell02 = NormalizeDouble(iMA_Short_Open_b*mypoint*sympoint, mydigit);
int iWPR_Short_ReverseA = 100 - iWPR_Short_Open_a;
int iWPR_Short_ReverseB = 100 - iWPR_Short_Open_b;
if (ATRFilter && ATR_Sell_Condition <= FilterATR * mypoint * sympoint) return (0);
if (MA_Sell_Condition - BaseClose > iMA_Sell01 && BaseClose - bid00 <= (mypoint * sympoint) && Stochastic_Sell_Condition > iWPR_Short_ReverseA) SellCon01 = TRUE;
else SellCon01 = FALSE;
if (MA_Sell_Condition - BaseClose > iMA_Sell02 && BaseClose - bid00 <= (mypoint * sympoint) && CCI_Sell_Condition > iCCI_OpenFilter) SellCon02 = TRUE;
else SellCon02 = FALSE;
if (MA_Sell_Condition - BaseClose > iMA_Sell02 && BaseClose - bid00 <= (mypoint * sympoint) && Stochastic_Sell_Condition > iWPR_Short_ReverseB) SellCon03 = TRUE;
else SellCon03 = FALSE;
if (SellCon01 == TRUE || SellCon02 == TRUE || SellCon03 == TRUE) SellCon = TRUE;
else SellCon = FALSE;
return (SellCon);
}
//******************************************************************************
//| Close Condition Function |
//******************************************************************************
//******************************************************************************
// CloseBuy Condition
bool CloseBuyCondition(int magic) {
bool CloseBuy = FALSE;
bool CloseBuyCon01 = FALSE;
bool CloseBuyCon02 = FALSE;
double Stochastic_CloseBuyCondition = iStochastic(NULL, TimeFrame, iWPR_PeriodLONG, iStoDperiod, iStoSlowingValue, MODE_SMA, 0, MODE_SIGNAL, ShiftTime);
double Close_BaseClose = iClose(NULL, TimeFrame, ShiftTime);
double Close_NowOpen = iOpen(NULL, PriceTimeFrame, ShiftTime);
double Close_NowClose = iClose(NULL, PriceTimeFrame, ShiftTime);
double StopPoint = NormalizeDouble(MinProfit * mypoint * sympoint, mydigit);
double ClosePricePoint = NormalizeDouble(Price_Filter_Close*mypoint*sympoint, mydigit);
if (FindLastBuyPrice(magic) - bid00 <= StopPoint && Close_BaseClose - bid00 <= (mypoint*sympoint) && Stochastic_CloseBuyCondition > iWPR_Filter_Close ) 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);
}
//******************************************************************************
// CloseSell Condition
bool CloseSellCondition(int magic) {
bool CloseSell = FALSE;
bool CloseSellCon01 = FALSE;
bool CloseSellCon02 = FALSE;
double Stochastic_CloseSellCondition = iStochastic(NULL, TimeFrame, iWPR_PeriodShort, iStoDperiod, iStoSlowingValue, MODE_SMA, 0, MODE_SIGNAL, ShiftTime);
double Close_BaseClose = iClose(NULL, TimeFrame, ShiftTime);
double Close_NowOpen = iOpen(NULL, PriceTimeFrame, ShiftTime);
double Close_NowClose = iClose(NULL, PriceTimeFrame, ShiftTime);
double StopPoint = NormalizeDouble(MinProfit * mypoint * sympoint, mydigit);
double ClosePricePoint = NormalizeDouble(Price_Filter_Close*mypoint*sympoint, mydigit);
int WPR_Reverse = 100 - iWPR_Filter_Close;
if (ask00 - FindLastSellPrice(magic) <= StopPoint && Close_BaseClose - bid00 >= (-mypoint*sympoint) && Stochastic_CloseSellCondition < WPR_Reverse ) 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);
}
'IT관련' 카테고리의 다른 글
메타트레이더 EA - BaseCurrency_RSI 2. Reverse Version (0) | 2019.09.10 |
---|---|
메타트레이더 EA - BaseCurrency_RSI 1. 기본 버전 (0) | 2019.09.09 |
메타트레이더 EA - USDCHF_Reverse (0) | 2019.09.08 |
메타트레이더 EA 3 (0) | 2019.08.30 |
메타트레이더 EA 2 (0) | 2019.08.30 |