☞ Named Pipe 기법을 이용하여 데이터를 전송받아 거래하는 EA, Chiggu에서 전송된 가격을 분석하여 주문을 내고(Open Spread), 청산(Close Spread)한다.
☞ 설치는 Chiggu1(서버명 gguri), Chiranai2(서버명 chiggu)를 하나의 Broker에 설치하고, 다른 Broker에 Chiggu2(서버명 chiggu), Chiranai1(서버명 gguri)를 설치하여 각기 다른 차트에 Attach, 즉 하나의 통화를 거래하기 위해서는 동일 TF, Symbol당 2개의 차트가 필요( 하나의 pipe를 이용하여 =>, 다른 pipe를 이용하여 <= )하다.
☞ 실제 청산은 ClosingTime에서 설정된 가격이후에 조건충족시 청산가능. 다른 Broker에 하나씩 설치되어 다른 서버명(gguri, chiggu)을 가지고 독립적으로 거래 및 청산을 수행한다.
☞ Real Test 결과 데모버전의 경우 Peak Time에서나 뉴스Time과 같이 변동성이 심한 경우 데모가 리얼에 비해 느려지는 현상이 발생하여 신호의 왜곡현상이 발생하여 V0.4에서는 Close 조건을 슬리피지 이상 수익발생하고 청산스프레드 충족시 청산으로 조건을 변경할 필요가 있다.
//******************************************************************************
//| YS_NP_Main_chiggu_V0.4 |
//| Copyright @ Gguri FX LAB |
//******************************************************************************
/*
Time Frame : Any Pairs
Pairs : EURUSD, GBPUSD, USDJPY, EURGBP, AUDUSD, USDCAD 등(브로커별로 확인요망)
Based Indicator : Named Pipe
Logic : Data Receiver/Trade EA (Named Pipe)
//******************************************************************************
//| Version History |
//******************************************************************************
0.1 Version
- Named Pipe mqh file(Clent, Server)을 이용하여 가격정보 전달 및 화면 표시 기능
- Named Pipe mqh file을 하나로 통합
- USDJPY 과 같은 통화에 대한 대응
- Named Pipe mqh file을 내재화
- Buy, Sell 조건의 기초작업(스프레드 차이 변수화 작업)
- Buy, Sell 주문 및 청산 로직 추가
- Pipe 추가 및 가격정보 역전송
- 수익계산 및 오더수 계산하여 화면표시
- Ready 추가
- Adjust함수 추가, magicnumber 수정
- 화면표시 정보수정
- Reverse와 분리
- Ready 내생변수
- Ready값에 따른 주문변경
- 화면표시 정보수정
- NewBar 수정을 통한 동시 주문 오류 확률 축소
0.2 Version
- TP, SL, Trailing, BreakEven 기능 추가
- 승률 계산 기능 추가
- 금일의 실적 화면 표시 기능 추가
0.3 Version
- 금일의 실적 화면 표시 기능 수정
0.4 Version
- 실전 Test 결과반영(Close 기능 대폭 수정)
*/
//******************************************************************************
//| 상수설정 |
//******************************************************************************
#define EA_NAME "YS_NP_Main_chiggu_V0.4"
#define Copyrights ""
#define Create_Date ""
//******************************************************************************
//| Import Library & Include |
//******************************************************************************
#import "stdlib.ex4"
string ErrorDescription(int a0);
// Named Pipe Include File Import
#define DEFAULT_MAX_PIPES 20
// Base name to use for pipe creation
#define PIPE_BASE_NAME "\\\\.\\pipe\\mt4-"
// *********************************************************************************************
// DLL imports and associated constants used by the pipe server
// *********************************************************************************************
#define GENERIC_READ 0x80000000
#define GENERIC_WRITE 0x40000000
#define OPEN_EXISTING 3
#define INVALID_HANDLE_VALUE -1
#define PIPE_ACCESS_DUPLEX 3
#define PIPE_UNLIMITED_INSTANCES 255
#define PIPE_NOWAIT 1
#define PIPE_TYPE_MESSAGE 4
#define PIPE_READMODE_MESSAGE 2
#define PIPE_WAIT 0
#import "kernel32.dll"
int CreateNamedPipeA(string pipeName,int openMode,int pipeMode,int maxInstances,int outBufferSize,int inBufferSize,int defaultTimeOut,int security);
int PeekNamedPipe(int PipeHandle, int PassAsZero, int PassAsZero2, int PassAsZero3, int & BytesAvailable[], int PassAsZero4);
int CreateFileA(string Filename, int AccessMode, int ShareMode, int PassAsZero, int CreationMode, int FlagsAndAttributes, int AlsoPassAsZero);
int CloseHandle(int fileHandle);
int ReadFile(int FileHandle, int BufferPtr, int BufferLength, int & BytesRead[], int PassAsZero);
int WriteFile(int FileHandle, string Buffer, int BufferLength, int & BytesWritten[], int PassAsZero);
int MulDiv(string X, int N1, int N2);
#import
//******************************************************************************
//| 내외생변수 설정 |
//******************************************************************************
//******************************************************************************
// Entry Logic 관련 변수 설정
extern string ref_entry_string = "Entry Settings";
int AccNumber01 = 706465; // Valid Account Number
extern string ServerNo1 = "chiggu"; // 서버이름설정, 통화마다 다르게 설정됨.
extern double openspread = 2.5; // 진입기준 스프레드(핍 기준)
extern double closespread = 1.5; // 청산기준 스프레드(핍 기준)
int MaxMessagesBetweenTicks = 50; // 메세지의 최대허용버퍼(200정도가 한계)
// int ClosingTime = 60; // 이익시 종결청산 처리시간 설정(초), 초기값 1분
bool Ready = false; // 진입기준 준비완료시 TRUE
int RetryForSeconds = 0;
int MessagesRetrieved;
double opens, closes, targetspread, clsspread, targetsell, clsbuy;
extern string order_set_string = "Order&Close Settings";
// 주문관련 변수설정
extern bool ECN = TRUE; // ECN Broker 주문처리 가능여부
extern double FixLot=0.1 ; // 진입 랏사이즈 설정
extern double slippage = 3.0; // 슬리피지 허용 변수
extern int XSL = 30; // StopLoss
extern int XTP = 30; // TakeProfit
// Trailing Stop/Break Even 관련 설정
extern double TrailingStop1 = 15.0; // Trailing Stop 설정시 > 0
extern double BreakEven1 = 12.0; // Break Even 설정시 > 0
extern double BreakPoint1 = 3.0; // Break Even 설정시 손절치(본전 + 손절치)
// 일괄청산관련 설정
extern bool CloseFilter = TRUE; // 청산시 기준 스프레드 사용여부
extern double StopOutBalance = 500; // 모든 거래 종료 잔고 설정
extern int All_SL = 150; // CloseAll StopLoss
extern int All_TP = 150; // CloseAll TakeProfit
//******************************************************************************
//| 제한조건 관련 설정(Max Spread, Max Trades, Day/Time Filter 등) |
//******************************************************************************
extern string limit_set_string = "Limitation Settings";
extern int MaxSpreads = 4; // 최대 허용 Spread(Pip), EURUSD,USDJPY-3, GBPUSD,EURGBP-4
extern int MaxTrades = 1; // 한방향 최대 주문건수
extern int MinBars = 100; // 최소 다운로드 Bar의 수
extern int MoneyEnable = 300; // 최소 거래 가능 금액 설정
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; // 금요일 거래종료시간
//******************************************************************************
//| 기타 내생 변수 설정 |
//******************************************************************************
string Commentary = EA_NAME; // Entry 주문시 비고
int mypoint; // 4 digit, 5digit broker에 대한 point 설정변수
string NowSym, StartDay; // EA 시작일 및 심볼 조정변수
int error_code; // 에러코드
/*
datetime PreviousBarTime1; // NewBarBuy 시간변수
datetime PreviousBarTime2; // NewBarSell 시간변수
*/
int magic; // magic number global variable 설정
string times,ServerN,PriceInfo;
// MarketInfo 정보를 받는 변수
string broker,servername,mytime;
double equity,reqmargin,stopout,minlot,maxlot,LotStep,sympoint,ask00,bid00,spread,accfree;
int leverage,mydigit,stoplevel,freeze;
double askprice, bidprice;
double myask, mybid;
// *********************************************************************************************
// Global variables used by the pipe server
// *********************************************************************************************
int glbPipeCount = DEFAULT_MAX_PIPES;
int glbPipe[DEFAULT_MAX_PIPES];
string glbPipeName;
// *********************************************************************************************
// Creates the pipe server. Used in init()
// *********************************************************************************************
void CreatePipeServer(string PipeName, int UsePipeInstances = DEFAULT_MAX_PIPES) {
// Store the number of pipe instances to use and resize the array accordinging
glbPipeCount = UsePipeInstances;
ArrayResize(glbPipe, glbPipeCount);
// Store the name to use for the pipe instances
glbPipeName = PipeName;
// Create the pipe instances
for (int i = 0; i < glbPipeCount; i++) {
glbPipe[i] = CreatePipeInstance();
}
return;
}
void DestroyPipeServer() {
for (int i = 0; i < glbPipeCount; i++) {
CloseHandle(glbPipe[i]);
}
return;
}
// *********************************************************************************************
// Checks for new messages. Used in start()
// *********************************************************************************************
int CheckForPipeMessages(string & arrMessages[]) {
int MessagesFound = 0;
for (int i = 0; i < glbPipeCount; i++) {
// Check each pipe instance for a message
string strMsg = CheckPipe(i);
if (strMsg != "") {
// If there is a message, add it to the list which we're passing back
MessagesFound++;
ArrayResize(arrMessages, MessagesFound);
arrMessages[MessagesFound - 1] = strMsg;
}
}
return (MessagesFound);
}
string CheckPipe(int PipeIndex) {
string strReturnValue = "";
// See if there's data available on the pipe
int BytesAvailable[1] = {0};
int res = PeekNamedPipe(glbPipe[PipeIndex], 0, 0, 0, BytesAvailable, 0);
if (res != 0) {
// PeekNamedPipe() succeeded
// Is there data?
if (BytesAvailable[0] != 0) {
// Keep reading until either we have all the data, or an error occurs
int TotalBytesRead = 0;
while (TotalBytesRead < BytesAvailable[0]) {
// Allocate a 200-byte buffer
string ReadBuffer = "01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789";
int BufferLength = StringLen(ReadBuffer);
// Read up to the maximum buffer size from the pipe. (The use of MulDiv() is an old trick from VB6 days for
// getting the address in memory of a string variable.)
int BytesRead[1] = {0};
ReadFile(glbPipe[PipeIndex], MulDiv(ReadBuffer, 1, 1), BufferLength, BytesRead, 0);
// Did we get any data from the read?
if (BytesRead[0] > 0) {
// Yes, got some data. Add it to the total message which is passed back
strReturnValue = StringConcatenate(strReturnValue, StringSubstr(ReadBuffer, 0, BytesRead[0]));
TotalBytesRead += BytesRead[0];
} else {
// No, the read failed. Stop reading, and pass back an empty string
strReturnValue = "";
TotalBytesRead = 999999;
}
}
// Destroy and recreate the pipe instance
CloseHandle(glbPipe[PipeIndex]);
glbPipe[PipeIndex] = CreatePipeInstance();
} else {
// No data available on pipe
}
} else {
// PeekNamedPipe() failed
}
return (strReturnValue);
}
int CreatePipeInstance() {
string strPipeName = StringConcatenate(PIPE_BASE_NAME , glbPipeName);
return (CreateNamedPipeA(strPipeName, GENERIC_READ | PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_NOWAIT, PIPE_UNLIMITED_INSTANCES, 1000, 1000, 0, NULL));
}
//******************************************************************************
//| 초기화 |
//******************************************************************************
int init()
{ // 1
// EA Validation Check
if(CheckValid()==FALSE) {
return(0);
}
// Period Protection
if(Period() != PERIOD_M1) {
Alert("1분봉 차트에 붙이셔야 합니다.");
return(0);
}
// Symbol Protection
if (StringSubstr(Symbol(), 0, 6) != "GBPUSD" && StringSubstr(Symbol(), 0, 6) != "EURUSD" && StringSubstr(Symbol(), 0, 6) != "USDJPY" && StringSubstr(Symbol(), 0, 6) != "EURGBP") {
Alert("GBPUSD,EURUSD,USDJPY,EURGBP 말고는 취급안해!");
return (0);
}
// EA 시작일 설정
StartDay = TimeToStr(TimeCurrent(),TIME_DATE);
// 통화별 매직넘버 가져오기
getmagic();
// 통화별 서버이름 재설정
ServerN = StringConcatenate( ServerNo1 , NowSym);
// Create the server
CreatePipeServer(ServerN, MaxMessagesBetweenTicks);
// 5 digit broker adjustment
if(MarketInfo(Symbol(), MODE_DIGITS)==3 || MarketInfo(Symbol(), MODE_DIGITS)==5) { // 2
mypoint = 10;
targetspread = -Point*openspread*mypoint;
targetsell = Point*openspread*mypoint;
clsspread = -Point*closespread*mypoint;
clsbuy = Point*closespread*mypoint;
} // 2
else
{ // 3
mypoint = 1;
targetspread = -Point*openspread*mypoint;
targetsell = Point*openspread*mypoint;
clsspread = -Point*closespread*mypoint;
clsbuy = Point*closespread*mypoint;
} // 3
return(0);
} // 1
//******************************************************************************
//| 종료시 설정 |
//******************************************************************************
int deinit() {
// Destroy the pipe server
DestroyPipeServer();
return(0);
}
//******************************************************************************
//| EA Start |
//******************************************************************************
int start() { // 0
//******************************************************************************
// Error 검출후 메세지 출력
// Server와 연결이 안된 경우
if(!IsConnected()) {
MessageBox("연결해주세요!");
return(0);
}
// DLL을 막아놓은 경우
if (!IsDllsAllowed()) { // 1
MessageBox("Allow DLL imports 를 확인해주세요.");
return(0);
} // 1
//******************************************************************************
// 데이타 다운로드 미비에 의한 오류계산 방지 로직
bool DataEnabled = TRUE;
if(iBars(Symbol(), 0) < MinBars) {
DataEnabled = FALSE;
Print ("아! Bar가 아직 모자라!ㅠㅠ..");
}
//******************************************************************************
// StopOut Balance도달시 강제청산함수 가져오기
StopOutClose();
//******************************************************************************
// Trailing Stop / Break Even 함수 가져오기
if(TrailingStop1>0) MoveTrailingStop(magic,TrailingStop1);
if(BreakEven1>0) MoveBreakEven(magic,BreakEven1,BreakPoint1);
//******************************************************************************
// MarketInfo 정보를 받는 변수 설정
broker = AccountCompany();
servername = AccountServer();
mytime = TimeToStr(TimeCurrent(),TIME_SECONDS);
equity = AccountEquity();
leverage = AccountLeverage();
reqmargin = MarketInfo(Symbol(), MODE_MARGINREQUIRED);
accfree = NormalizeDouble(AccountFreeMargin(),2);
double ask00 = MarketInfo(Symbol(),MODE_ASK);
double bid00 = MarketInfo(Symbol(),MODE_BID);
myask = adjust(ask00); // 현재 차트 ASK Price
mybid = adjust(bid00); // 현재 차트 BID Price
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);
//******************************************************************************
//| Date/Time Filter |
//******************************************************************************
// Spread조건 및 Day/Time Filter충족여부 검토
bool DateEnabled = FALSE;
if (TradeEnable() && DayFilter()) DateEnabled = TRUE;
else DateEnabled = FALSE;
//******************************************************************************
// 잔고가 일정액 이하인 경우 EA 진입금지
bool EnoughMoney = TRUE;
if(accfree < MoneyEnable) {
Print("돈이 없어. 현잔고 = ", accfree);
EnoughMoney = FALSE;
}
else EnoughMoney = TRUE;
//******************************************************************************
bool EntryEnabled = FALSE;
if (DataEnabled && DateEnabled && EnoughMoney) EntryEnabled = TRUE;
else EntryEnabled = FALSE;
// 토요일, 일요일 거래 제한
if ( DayOfWeek() == 0 || DayOfWeek() == 6 ) EntryEnabled = FALSE;
//******************************************************************************
//| 전송된 파이프 데이타 자료를 처리 |
//******************************************************************************
string GetPrices[]; // 전송받은 데이타를 문자열 배열로 받는다.
int senddigit; // 전송받은 데이타 가운데 자리수를 숫자로 변환.
MessagesRetrieved = CheckForPipeMessages(GetPrices); // 데이타의 크기를 확인
string Datas[2]; // 전송받은 데이타를 문자열 배열로 받는다.
//******************************************************************************
// 전송받은 데이타를 Parsing하고, 원래 데이타로 환원후 표시
if (MessagesRetrieved > 0) { // 1
for (int i = 0; i < MessagesRetrieved; i++) { // 2
senddigit = StrToInteger(StringSubstr(GetPrices[i],0,1));
times = StringSubstr(GetPrices[i],1,8);
Datas[0] = StringSubstr(GetPrices[i],10,7);
Datas[1] = StringSubstr(GetPrices[i],18,7);
askprice = StrToDouble(Datas[0]);
bidprice = StrToDouble(Datas[1]);
double buyspread = myask - bidprice;
double sellspread = mybid - askprice;
} // 2
} // 1
//******************************************************************************
//| 진입청산 조건 설정 |
//******************************************************************************
bool buycon = false;
bool sellcon = false;
bool clsbuycon = false;
bool clssellcon = false;
if (buyspread < targetspread) buycon = true;
if (sellspread > targetsell) sellcon = true;
if (sellspread > clsbuy) clsbuycon = true;
if (buyspread < clsspread) clssellcon = true;
if (buycon || sellcon) {Ready = true;}
else {Ready = false;}
//******************************************************************************
//| Close Condition Function |
//******************************************************************************
//******************************************************************************
// Close 조건 충족시 청산
// V0.4 : Slippage이상 수익 발생시 청산
if(CloseFilter && TotalBuyOrders(magic)>0 && BProfit(magic)>slippage && clsbuycon) CloseBuyOpens(magic);
if(CloseFilter && TotalSellOrders(magic)>0 && SProfit(magic)>slippage && clssellcon) CloseSellOpens(magic);
//******************************************************************************
// 전체수익이나 손실이 설정치 이상인 경우 Close All
bool ProfitReady = FALSE;
double profits = Profit(magic);
if((TotalOrders(magic)>1) && (profits>All_TP || profits<-All_SL)) CloseAllOpens(magic);
/*
// PENDING ORDER Processing
pos_buy=0; // open buy contracts
pos_sell=0; // open sell contracts
// 현재 open position 검토후 Chiranai EA에 의한 주문건 처리
RefreshRates();
for (int k=0; k<OrdersTotal(); k++) { // 5
// 시간경과후 조건충족시 청산
OrderSelect(k,SELECT_BY_POS,MODE_TRADES);
if ( OrderSymbol()==Symbol() && OrderMagicNumber()==magic ) { // 6
if (OrderType()==OP_BUY) { // 7
if ( (TimeCurrent()-OrderOpenTime() >= ClosingTime) && clsbuycon==true ) { // 8
OrderClose(OrderTicket(),OrderLots(),MarketInfo(Symbol(),MODE_BID),slippage,Red);
Print("청산spread : " + sellspread);
return(0);
} // 8
pos_buy++;
} // 7
if (OrderType()==OP_SELL) { // 9
if ( (TimeCurrent()-OrderOpenTime() >= ClosingTime) && clssellcon==true ) { // 10
OrderClose(OrderTicket(),OrderLots(),MarketInfo(Symbol(),MODE_ASK),slippage,Red);
Print("청산spread : " + buyspread);
return(0);
} // 10
pos_sell++;
} // 9
} // 6
} // 5
*/
// PENDING ORDER END
//******************************************************************************
//| Order 주문처리 Logic |
//******************************************************************************
bool BuyEntry = FALSE;
bool SellEntry = FALSE;
int ticketbuy, ticketsell;
if(Ready && (MessagesRetrieved > 0) && buycon && (TotalBuyOrders(magic) < MaxTrades)) BuyEntry = TRUE;
else BuyEntry = FALSE;
if(EntryEnabled && BuyEntry) ticketbuy = OpenOrder(Symbol(),OP_BUY,FixLot,slippage,XSL,XTP,magic);
if(Ready && (MessagesRetrieved > 0) && sellcon && (TotalSellOrders(magic) < MaxTrades)) SellEntry = TRUE;
else SellEntry = FALSE;
if(EntryEnabled && SellEntry) ticketsell = OpenOrder(Symbol(),OP_SELL,FixLot,slippage,XSL,XTP,magic);
//******************************************************************************
//| 전송 데이타와 전송받은 데이타 화면표시 |
//******************************************************************************
// 화면표시 변수 정의
double TlLots = TotalLot(magic);
double hprofit = HistoryProfit(magic);
int orders = TotalOrders(magic);
int borders = TotalBuyOrders(magic);
int sorders = TotalSellOrders(magic);
int hborders = HBuyOrders(magic);
int hsorders = HSellOrders(magic);
int horders = hborders+hsorders;
int hwborders = HWBuyOrders(magic);
int hwsorders = HWSellOrders(magic);
double hworders = hwborders+hwsorders;
double bprofits = BProfit(magic);
double sprofits = SProfit(magic);
double hbprofit = HBProfit(magic);
double hsprofit = HSProfit(magic);
double HTLots = HTotalLot(magic);
double TWinRatio;
if(horders>0) {
TWinRatio = hworders/horders;
}
else {
TWinRatio = 0.00;
}
double TotalWRatio = NormalizeDouble(TWinRatio*100,2);
string symbolpoint = DoubleToStr(sympoint,Digits);
string strspread = DoubleToStr(spread,Digits);
string maxspread = DoubleToStr(MaxSpreads*mypoint*sympoint,Digits);
string Trades;
if (Ready == false) { // 0
Trades = "기둘,...";
} // 0
else
{ // 1
Trades = "신호나왔어";
} // 1
string ScreenStr;
ScreenStr = StringConcatenate("EA Name : ",EA_NAME," , 접속명 : ",ServerN," , Copyright : ",Copyrights," , EA제작일_",Create_Date," 평가잔액 = $",equity," Leverage_",leverage,":1, 1Lot당 필요증거금 : $",reqmargin)+"\n";
ScreenStr = ScreenStr + StringConcatenate("Broker : ",broker," Server : ",servername," EA시작일_",StartDay," StopLevel_",stoplevel," Freeze Level_",freeze," Stop Out_",stopout,"%, Digit_",mydigit,", Entry_",EntryEnabled)+"\n";
ScreenStr = ScreenStr + StringConcatenate("Point_",symbolpoint," Min Lot_",minlot," Max Lot_",maxlot," Lot Step_",LotStep," Max Spread_",maxspread," Spread_",strspread," Data_",DataEnabled," Date_",DayFilter())+"\n";
ScreenStr = ScreenStr + "===========================================================================================================" + "\n";
ScreenStr = ScreenStr + StringConcatenate("My Ask = ",DoubleToStr(myask,Digits)," , My Bid = ",DoubleToStr(mybid,Digits)," , 현재시간 : ",mytime)+"\n";
ScreenStr = ScreenStr + StringConcatenate("R_Time : ",times," , R_ASK : ",Datas[0]," , R_BID : ",Datas[1]," , CloseBuy : ",DoubleToStr(clsbuy,Digits)," , CloseSell : ",DoubleToStr(clsspread,Digits))+"\n";
ScreenStr = ScreenStr + StringConcatenate("BuySpread : ",DoubleToStr(buyspread,Digits)," , BuyTarget : ",DoubleToStr(targetspread,Digits)," , SellSpread : ",DoubleToStr(sellspread,Digits)," , SellTarget : ",DoubleToStr(targetsell,Digits))+"\n";
ScreenStr = ScreenStr + StringConcatenate("Order Ready? : ",Trades," , BuyCon : ", buycon," , SellCon : ", sellcon, " , ClsBuy : ",clsbuycon," , ClsSell : ",clssellcon, " , New Profits : ",profits,", New Orders : ",orders,"건 = Buy ",borders,"건 / Sell",sorders,"건") + "\n";
ScreenStr = ScreenStr + "===========================================================================================================" + "\n";
ScreenStr = ScreenStr + StringConcatenate("총현재오더 : ",profits,", New Orders : ",TlLots,"Lot_",orders,"건 = Buy $",bprofits,"_",borders,"건 / Sell $",sprofits,"_",sorders,"건, 금일 승률_",TWinRate(magic),"% 금일 수익_$",TProfits(magic)) + "\n";
ScreenStr = ScreenStr + "================================================================" + "\n";
ScreenStr = ScreenStr + StringConcatenate("전체 과거 : $",hprofit,", Buy : $",hbprofit,", Sell : $",hsprofit,", Total Buy : ",hwborders,"/",hborders,"건, Total Sell : ",hwsorders,"/",hsorders,"건, Total Orders : ",HTLots,"Lot_",hwborders+hwsorders,"/",horders,"건, 승률_",TotalWRatio,"%");
Comment(ScreenStr);
return(0);
} // 0
//******************************************************************************
//| EA Valid Check Function |
//******************************************************************************
bool CheckValid() {
if (!IsDemo() && !AccountNumber()==AccNumber01) {
Alert("좋은 말할 때 돈내고 쓰세요!");
return(FALSE);
}
else return(TRUE);
}
//******************************************************************************
// Max Spread Limitation 설정함수 |
//******************************************************************************
bool TradeEnable() {
if(ask00-bid00 > MaxSpreads*mypoint*sympoint) return(false);
else return(true);
}
/*
//******************************************************************************
//| Allow One Action Per Bar |
//******************************************************************************
// 현재 바에서 하나만 주문할때 사용하는 함수
bool NewBarBuy() { // 0
if(PreviousBarTime1<Time[0]) { // 1
PreviousBarTime1=Time[0];
return(true);
} // 1
return(false);
} // 0
bool NewBarSell() { // 2
if(PreviousBarTime2<Time[0]) { // 3
PreviousBarTime2=Time[0];
return(true);
} // 3
return(false);
} // 2
bool NewBar() { // 4
static datetime lastbar = 0;
if(lastbar!=Time[0]) { // 5
lastbar=Time[0];
return (true);
} // 5
return(false);
} // 4
*/
//******************************************************************************
//| 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
//******************************************************************************
//| 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
//******************************************************************************
//| 자리수 조정 함수 |
//******************************************************************************
double adjust(double gets)
{ // 0
double ad;
if (gets >= 0 && gets < 10) ad = NormalizeDouble(gets, 5);
if (gets >=10 && gets < 100) ad = NormalizeDouble(gets, 4);
if (gets >=100 && gets < 1000) ad = NormalizeDouble(gets, 3);
if (gets >=1000 && gets < 10000) ad = NormalizeDouble(gets, 2);
if (gets >=10000 && gets < 100000) ad = NormalizeDouble(gets, 1);
return (ad);
} // 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(),MarketInfo(OrderSymbol(),MODE_BID),5,Red);
break;
case OP_SELL : resultall = OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_ASK),5, Blue);
} //switch
if(resultall == false) { // 17
Print("Order ", OrderTicket(), " failed to close. Error:", GetLastError() );
} // 17
} // 16
} // 15
} // 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);
}
}
}
}
}
}
}
}
//******************************************************************************
//| 통화별 매직넘버 설정 |
//******************************************************************************
int getmagic()
{
// 접미사형태의 통화대처를 위해 심볼명의 6자리까지 심볼명으로 지정
NowSym = StringSubstr(Symbol(), 0, 6);
if(NowSym == "EURUSD") magic = 13978001;
if(NowSym == "GBPUSD") magic = 13978002;
if(NowSym == "USDJPY") magic = 13978003;
if(NowSym == "AUDUSD") magic = 13978004;
if(NowSym == "EURGBP") magic = 13978005;
if(NowSym == "USDCAD") magic = 13978006;
if(NowSym == "USDCHF") magic = 13978007;
if(NowSym == "CHFJPY") magic = 13978008;
if(NowSym == "EURJPY") magic = 13978009;
if(NowSym == "NZDUSD") magic = 13978010;
if(NowSym == "GBPJPY") magic = 13978011;
if(NowSym == "EURAUD") magic = 13978012;
if(NowSym == "EURCAD") magic = 13978013;
if(NowSym == "EURCHF") magic = 13978014;
if(NowSym == "CADJPY") magic = 13978015;
if(NowSym == "AUDNZD") magic = 13978016;
if(NowSym == "AUDCAD") magic = 13978017;
if(NowSym == "AUDCHF") magic = 13978018;
if(NowSym == "AUDJPY") magic = 13978019;
if(NowSym == "GBPAUD") magic = 13978020;
if(NowSym == "NZDJPY") magic = 13978021;
if(NowSym == "GBPCAD") magic = 13978022;
if(NowSym == "NZDCAD") magic = 13978023;
if(NowSym == "CADCHF") magic = 13978024;
if(NowSym == "GBPNZD") magic = 13978025;
if(NowSym == "EURNZD") magic = 13978026;
if(NowSym == "NZDCHF") magic = 13978027;
if(NowSym == "GBPCHF") magic = 13978028;
return(magic);
}
//******************************************************************************
//| 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);
}
//******************************************************************************
//| Close All By Magic Number |
//******************************************************************************
void CloseAllOpens(int Magic) { // 함수 시작
int total = OrdersTotal();
double asks = MarketInfo(Symbol(),MODE_ASK);
double bids = MarketInfo(Symbol(),MODE_BID);
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) { // magic 조건시작
RefreshRates();
switch(type) { // Order Type 검색 및 처리
//Close opened long positions
case OP_BUY : result = OrderClose( OrderTicket(), OrderLots(), bids, slippage, Blue );
break;
//Close opened short positions
case OP_SELL : result = OrderClose( OrderTicket(), OrderLots(), asks, slippage, Red );
} // Order Type 검색 및 처리 종료
if(result == false) { // 에러 처리
Alert("Order " , OrderTicket() , " failed to close. Error:" , GetLastError() );
Sleep(3000);
} // 에러 처리 종료
} // magic 조건종료
} // Loop 종료
} // 함수 종료
//******************************************************************************
//| CloseBuy By Magic Number |
//******************************************************************************
void CloseBuyOpens(int Magic) { // 함수 시작
int total = OrdersTotal();
double bids = MarketInfo(Symbol(),MODE_BID);
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 조건시작
result = OrderClose( OrderTicket(), OrderLots(), bids, slippage, Blue );
if(result == false) { // 에러 처리
Alert("Order " , OrderTicket() , " failed to close. Error:" , GetLastError() );
Sleep(3000);
} // 에러 처리 종료
} // magic 조건종료
} // Loop 종료
} // 함수 종료
//******************************************************************************
//| CloseSell By Magic Number |
//******************************************************************************
void CloseSellOpens(int Magic) { // 함수 시작
int total = OrdersTotal();
double asks = MarketInfo(Symbol(),MODE_ASK);
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 조건시작
result = OrderClose( OrderTicket(), OrderLots(), asks, slippage, Blue );
if(result == false) { // 에러 처리
Alert("Order " , OrderTicket() , " failed to close. Error:" , GetLastError() );
Sleep(3000);
} // 에러 처리 종료
} // magic 조건종료
} // Loop 종료
} // 함수 종료
//******************************************************************************
//| 주문 함수 (OpenOrder) |
//******************************************************************************
int OpenOrder( string SymbolName, int CmdType, double Lots, int Slippages, double StopLosses, double TakeProfit, int magic) { // 함수 시작
static string OrderTypeToString[6] = {"OP_BUY", "OP_SELL", "OP_BUYLIMIT", "OP_SELLLIMIT", "OP_BUYSTOP", "OP_SELLSTOP"};
double ask00 = MarketInfo(SymbolName,MODE_ASK);
double bid00 = MarketInfo(SymbolName,MODE_BID);
int Ticket = -1;
int ErrorCodes;
int Slips = 0;
double Vol = 0;
string Comments;
color CLRs;
RefreshRates();
double stopbuy = NormalizeDouble(ask00-(StopLosses*mypoint*MarketInfo(SymbolName,MODE_POINT)),MarketInfo(SymbolName, MODE_DIGITS));
double stopsell = NormalizeDouble(bid00+(StopLosses*mypoint*MarketInfo(SymbolName,MODE_POINT)),MarketInfo(SymbolName, MODE_DIGITS));
double tpbuy = NormalizeDouble(ask00+(TakeProfit*mypoint*MarketInfo(SymbolName,MODE_POINT)),MarketInfo(SymbolName, MODE_DIGITS));
double tpsell = NormalizeDouble(bid00-(TakeProfit*mypoint*MarketInfo(SymbolName,MODE_POINT)),MarketInfo(SymbolName, MODE_DIGITS));
if (StopLosses == 0) {
stopbuy = 0;
stopsell = 0;
}
if (TakeProfit == 0) {
tpbuy = 0;
tpsell = 0;
}
if (StopLosses == 0 && TakeProfit == 0) ECN = FALSE;
if (CmdType == OP_BUY) { // Buy 시작
Comments = Commentary+"샀어";
CLRs = Red;
if (ECN == true) { // ECN 시작
double execution = GetTickCount();
Ticket = OrderSend(SymbolName, CmdType, Lots, ask00, Slippages, 0, 0,Comments,magic,0,CLRs);
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(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+"팔았어";
CLRs = Blue;
if (ECN == true) { // ECN 시작
execution = GetTickCount();
Ticket = OrderSend(SymbolName, CmdType, Lots, bid00, Slippages, 0, 0,Comments,magic,0,CLRs);
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(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);
}
'IT관련' 카테고리의 다른 글
메타트레이더 EA - RT IlmokCloud (0) | 2019.09.20 |
---|---|
메타트레이더 EA - Named Pipe Sub (0) | 2019.09.19 |
메타트레이더 EA - GV Import (0) | 2019.09.17 |
메타트레이더 EA - GV Export (0) | 2019.09.16 |
Entry Logic 구성 Indicator(Backtest) (0) | 2019.09.15 |