//#include <mql4-http.mqh>
extern double Lot = 0.01; // Lots to Trade
extern int EA_Magic = 24290; // EA Magic Number
extern int Slippage = 2; //Slippage in pips
extern int MAX_ORDER = 5;
extern double TakeProfit=15;
extern double StopLoss=20;
extern bool isCloseOnChangeSignal = false;
string comment = "";
string doAllBuySignal = "doAllBuySignal";
string doAllSellSignal = "doAllSellSignal";
string getAllBuySymbol = "getAllBuySymbol";
string getAllSellSymbol = "getAllSellSymbol";
string mainURL = "http://localhost/Jatin_Team/index.jsp?action=";
int OnInit() {
//check for buy
}
void OnDeinit(const int reason) {
}
void OnTick() {
//if(!market_open()) return;
int totalOrd = getTotalOpenedOrder();
if (totalOrd <= MAX_ORDER) { // code for opened order
//check for buy
string buystr[];
if (doRequest(doAllBuySignal, buystr)) {
takeAction(buystr,OP_BUY);
}
//check for sell
string sellstr[];
if (doRequest(doAllSellSignal, sellstr)) {
takeAction(sellstr,OP_SELL);
}
setTakeProfitStopLoss();
}else if(totalOrd != 0){
if(isCloseOnChangeSignal){
watchForOpen();
}
}
}
void setTakeProfitStopLoss(){
int digits=MarketInfo("EURUSD",MODE_DIGITS);
int StopMultd = 0;
if(digits==5){StopMultd=10;} else{StopMultd=1;}
double TP=NormalizeDouble(TakeProfit*StopMultd,Digits);
double SL=NormalizeDouble(StopLoss*StopMultd,Digits);
double slb=0;
double sls=0;
double tpb=0;
double tps=0;
if(OrdersTotal()>0){
for(int i=1; i<=OrdersTotal(); i++) // Cycle searching in orders
{
if (OrderSelect(i-1,SELECT_BY_POS)==true) // If the next is available
{
TP=NormalizeDouble(TakeProfit*StopMultd,Digits);
SL=NormalizeDouble(StopLoss*StopMultd,Digits);
if((OrderType()==OP_BUY)&&((OrderTakeProfit()==0)))
{
slb=NormalizeDouble(OrderOpenPrice()-SL*Point,Digits);
tpb=NormalizeDouble(OrderOpenPrice()+TP*Point,Digits);
OrderModify(OrderTicket(),0,slb,tpb,0,CLR_NONE);
}
if((OrderType()==OP_SELL)&&(OrderTakeProfit()==0))
{
sls=NormalizeDouble(OrderOpenPrice()+SL*Point,Digits);
tps=NormalizeDouble(OrderOpenPrice()-TP*Point,Digits);
OrderModify(OrderTicket(),0,sls,tps,0,CLR_NONE);
}
}
}
}
}
void watchForOpen(){
string symbol = NULL;
int Type = -1;
string AllBuySymbol[];
doRequest(getAllBuySymbol,AllBuySymbol);
string AllSellSymbol[];
doRequest(getAllSellSymbol,AllSellSymbol);
double ClosePrice=0;
double Lots=0;
int Ticket=0;
bool res= false;
for (int i = OrdersTotal() - 1; i >= 0; i--) // returns the number of open positions
{
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
if (OrderMagicNumber() == EA_Magic ) {
symbol = OrderSymbol();
string reverseSym = getReverseSym(symbol);
Type = OrderType();
if(Type == OP_BUY){
if(chekIfInList(AllSellSymbol,symbol) ){ // do close action
ClosePrice=Bid;
Lots=OrderLots();
Ticket=OrderTicket();
res=OrderClose(Ticket,Lots,ClosePrice,Slippage,Red);
if(!res){
Print("ERROR - CLOSE - error closing order ",Ticket," return error: ",GetLastError());
}
}else if(chekIfInList(AllBuySymbol,reverseSym)){
ClosePrice=Bid;
Lots=OrderLots();
Ticket=OrderTicket();
res=OrderClose(Ticket,Lots,ClosePrice,Slippage,Red);
if(!res){
Print("ERROR - CLOSE - error closing order ",Ticket," return error: ",GetLastError());
}
}
}else if(Type == OP_SELL){
if(chekIfInList(AllBuySymbol,symbol)){
ClosePrice=Ask;
Lots=OrderLots();
Ticket=OrderTicket();
res=OrderClose(Ticket,Lots,ClosePrice,Slippage,Red);
if(!res){
Print("ERROR - CLOSE - error closing order ",Ticket," return error: ",GetLastError());
}
}else if(chekIfInList(AllSellSymbol,reverseSym)){
ClosePrice=Ask;
Lots=OrderLots();
Ticket=OrderTicket();
res=OrderClose(Ticket,Lots,ClosePrice,Slippage,Red);
if(!res){
Print("ERROR - CLOSE - error closing order ",Ticket," return error: ",GetLastError());
}
}
}
}
}
}
Sleep(60000);
}
bool chekIfInList(string & str[],string paramSymbol) {
int size = ArraySize(str);
string symbol = "";
for (int i = 0; i < size; i++) {
symbol = str[i];
if (symbol != NULL && symbol != "") {
if(paramSymbol == symbol){
return true;
}
}
}
return false;
}
void takeAction(string & str[],int action) {
string symbol = "";
int size = ArraySize(str);
for (int i = 0; i < size; i++) {
symbol = str[i];
if (symbol != NULL && symbol != "") {
if(!isSymbolOpened(symbol)){
getRightSymbol(symbol,action);
}
}
}
}
void getRightSymbol(string symbol,int action){
if(checkIfSymbolExists(symbol)){
if (action == OP_BUY) {
buy(symbol);
}else if(action == OP_SELL){
sell(symbol);
}
}else{
string finalSymbol = getReverseSym(symbol);
if(checkIfSymbolExists(finalSymbol)){
//Symbol Reversed
if (action == OP_SELL ) {
buy(finalSymbol);
}else if(action == OP_BUY){
sell(finalSymbol);
}
}
}
}
string getReverseSym(string symbol){
string first = StringSubstr(symbol,0,3);
string last = StringSubstr(symbol,3);
string finalSymbol = StringConcatenate(last,first);
return finalSymbol;
}
bool checkIfSymbolExists(string symbol){
ResetLastError();
double bid=MarketInfo(symbol,MODE_BID);
if(GetLastError()==4106){
return(false);
}else {
return(true);
} // unknown symbol
}
// symbol_size = StringSplit(reqPair, StringGetCharacter(";", 0), EA_Symbols_Array);
/*
void dosplit(string str,string &rep[]){
if(str !=NULL || str != "-1"){
StringSplit(str, StringGetCharacter(";", 0), rep);
}
}
*/
bool isSymbolOpened(string symbol) {
bool isSymbol = false;
string reverseSym = getReverseSym(symbol);
for (int i = OrdersTotal() - 1; i >= 0; i--) // returns the number of open positions
{
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
if (OrderMagicNumber() == EA_Magic ) {
if ( OrderSymbol() == symbol || OrderSymbol() == reverseSym ) {
return true;
}
}
}
}
return isSymbol;
}
int getTotalOpenedOrder() {
int isPairOpen = 0;
for (int i = OrdersTotal() - 1; i >= 0; i--) // returns the number of open positions
{
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
if (OrderMagicNumber() == EA_Magic) {
isPairOpen++;
}
}
}
return isPairOpen;
}
bool isSymbolOpenInHist(string symbol){
for(int i=OrdersHistoryTotal()-1;i>=0;i--)
{
if (!OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) continue;
if(OrderSymbol()==symbol && OrderMagicNumber()==EA_Magic)
{
datetime orderclosetime = OrderCloseTime();
datetime rr = orderclosetime +3600*1;
datetime currentTime = TimeCurrent();
if(currentTime < rr){
return true;
}else{
return false;
}
// int h=TimeHour(TimeCurrent());
//for buy order
// if(OrderType()==OP_BUY && OrderClosePrice()>=OrderOpenPrice()) last="profit";
// if(OrderType()==OP_BUY && OrderClosePrice()<=OrderOpenPrice()) last="loss";
}
}
return false;
}
bool buy(string symbol) {
return openBuySell(OP_BUY, symbol);
}
bool sell(string symbol) {
return openBuySell(OP_SELL, symbol);
}
bool openBuySell(int Type, string symbol) {
if(isSymbolOpenInHist(symbol))
return true;
bool res = false;
color l_color;
double l_price, l_sprice, l_stoploss = 0;
RefreshRates();
double TakeProfit = 0 , StopLoss = 0 ;
if (Type == OP_BUY) {
l_price=MarketInfo(symbol,MODE_ASK);
l_color = Blue;
// double Spread = Ask - Bid;
// TakeProfit = MarketInfo(symbol,MODE_BID) + Take_Profit_Pip * MarketInfo(symbol,MODE_POINT));
// StopLoss = MarketInfo(symbol,MODE_BID) - Stop_Loss_Pip * MarketInfo(symbol,MODE_POINT));
}
if (Type == OP_SELL) {
l_price= MarketInfo(symbol,MODE_BID);
l_color = Red;
// TakeProfit = MarketInfo(symbol,MODE_BID) - Take_Profit_Pip * MarketInfo(symbol,MODE_POINT));
// StopLoss = MarketInfo(symbol,MODE_BID) + Stop_Loss_Pip * MarketInfo(symbol,MODE_POINT));
}
// Send order
int l_ticket = OrderSend(symbol, Type, Lot, l_price, Slippage, StopLoss, TakeProfit, comment, EA_Magic, 0, l_color);
// Rety if failure
if (l_ticket == -1) {
res = false;
} else {
res = true;
}
return res;
}
bool doRequest(string action, string & response[]) {
string cookie = NULL, headers;
// response = NULL;
bool sucess = false;
char post[], resultReq[];
string result;
int res;
//--- to enable access to the server, you should add URL "https://www.google.com/finance"
//--- in the list of allowed URLs (Main Menu->Tools->Options, tab "Expert Advisors"):
string google_url = mainURL + action;
// google_url = "http://localhost/Jatin_Team/index.jsp";
//--- Reset the last error code
ResetLastError();
//--- Loading a html page from Google Finance
int timeout = 15000; //--- Timeout below 1000 (1 sec.) is not enough for slow Internet connection
res = WebRequest("GET", google_url, cookie, NULL, timeout, post, 0, resultReq, headers);
//--- Checking errors
if (res == -1) {
Print("Error in WebRequest. Error code =", GetLastError());
//--- Perhaps the URL is not listed, display a message about the necessity to add the address
// MessageBox("Add the address '" + google_url + "' in the list of allowed URLs on tab 'Expert Advisors'", "Error", MB_ICONINFORMATION);
} else {
/*
//--- Load successfully
PrintFormat("The file has been successfully loaded, File size =%d bytes.",ArraySize(resultReq));
//--- Save the data to a file
int filehandle=FileOpen("GoogleFinance.htm",FILE_WRITE|FILE_BIN);
//--- Checking errors
if(filehandle!=INVALID_HANDLE)
{
//--- Save the contents of the resultReq[] array to a file
FileWriteArray(filehandle,resultReq,0,ArraySize(resultReq));
//--- Close the file
FileClose(filehandle);
}
else Print("Error in FileOpen. Error code=",GetLastError());
*/
result = CharArrayToString(resultReq,0,WHOLE_ARRAY,65001);
// buy(result);
// checkIfSymbolExists(result);
// return sucess;
// result = httpGET(google_url);
}
int len = StrToInteger(result);
if (len != -1 ) {
StringSplit(result, StringGetCharacter(",", 0), response);
sucess = true;
}
return sucess;
}
bool market_open()
{
string symbol = "EURUSD";
if(StringLen(symbol)>1)
{
datetime begin=0;
datetime end=0;
datetime now=TimeCurrent();
uint session_index=0;
MqlDateTime today;
TimeToStruct(now,today);
if(SymbolInfoSessionTrade(symbol,(ENUM_DAY_OF_WEEK) today.day_of_week,session_index,begin,end)==true)
{
string snow=TimeToString(now,TIME_MINUTES|TIME_SECONDS);
string sbegin=TimeToString(begin,TIME_MINUTES|TIME_SECONDS);
string send=TimeToString(end-1,TIME_MINUTES|TIME_SECONDS);
now=StringToTime(snow);
begin=StringToTime(sbegin);
end=StringToTime(send);
if(now>=begin && now<=end)
return true;
return false;
}
else return false;
}
Print("invalid symbol!!!!!");
return false;
}
********************************
<%@ page language="java" import="java.util.*"%>
<%@page import="com.jatin.*"%>
<%@ page language="java" import="java.io.*"%>
<%
String resp = "-1";
// try {
// String requestParam = request.getParameter("action");
// Action action = new Action();
// if ("doAllBuySignal".equalsIgnoreCase(requestParam)) {
// resp = Util.process(action.doFilterBuySignal());
// } else if ("doAllSellSignal".equalsIgnoreCase(requestParam)) {
// resp = Util.process(action.doFilterSellSignal());
// } else if ("getAllBuySymbol".equalsIgnoreCase(requestParam)) {
// resp = Util.process(action.getAllBuySymbol());
// } else if ("getAllSellSymbol".equalsIgnoreCase(requestParam)) {
// resp = Util.process(action.getAllSellSymbol());
// }
// } catch (Exception e) {
// System.out.println(e);
// resp = "-1";
// }
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
// PrintWriter om = response.getWriter();
// om.println("GBPUSD");
ServletOutputStream O = response.getOutputStream();
O.write("EURUSD,USDJPY,AUDUSD".getBytes("UTF-8"));
O.flush();
O.close();
%>