BuySEll scalp
//+------------------------------------------------------------------+
//| BuySellScalp.mq5 |
//| Copyright 2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"
#define REASON_SL 2
#include <Trade\Trade.mqh>
CTrade trade;
input string TradeStartTime = "00:00";
input string TradeStopTime = "13:25";
input bool Monday = true;
input bool Tuesday = true;
input bool Wednesday = true;
input bool Thursday = true;
input bool Friday = true;
input bool Saturday = true;
input bool Sunday = true;
input long MagicNumber=12345;
input double MaxLot=20;
input double Quantity=20;
input bool Positional=true;
input double InitialTradeSl=5;
input double InitialTradeTarget=5;
input double InitialSlCount=5;
input double TradeDist=5;
input double InitialTradeDist=5;
int slcount=0;
bool runonce = false,EAActivated = false;
double bid,ask,ltp;
string Trend=NULL;
double buylevel,selllevel,Buy_uptgt,Buy_upsll,Buy_downtgt,Buy_downsll,sell_uptgt,sell_upsll,sell_downtgt,sell_downsll;
bool buyupsll=false,buydownsll=false,sellupsll=false,selldownsll=false,buyuptgt=false,buydowntgt=false,selluptgt=false,selldowntgt=false;
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
string ArrayToString(double &arr[])
{
string result = "[";
for(int i = 0; i < ArraySize(arr); i++)
{
result += DoubleToString(arr[i], 2);
if(i < ArraySize(arr) - 1)
result += ",";
}
result += "]";
return result;
}
double parts[];
void SplitIntoParts(int total, int part, double &parts[])
{
// Calculate the number of full parts
int fullParts = total / part;
// Add the full parts to the array
for(int i = 0; i < fullParts; i++)
{
ArrayResize(parts, ArraySize(parts) + 1);
parts[ArraySize(parts) - 1] = part; // These are guaranteed to be integers
}
// Calculate the remainder
int remainder = total % part;
// If there is a remainder, add it to the array
if(remainder > 0)
{
ArrayResize(parts, ArraySize(parts) + 1);
parts[ArraySize(parts) - 1] = remainder; // Remainder might not be an integer
}
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
int OnInit()
{
//---
SplitIntoParts(Quantity,MaxLot, parts);
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
lastclosedorder();
datetime current_time = TimeCurrent();
MqlDateTime current_datetime;
TimeToStruct(current_time, current_datetime);
int current_day_of_week = current_datetime.day_of_week;
datetime start_time = StringToTime(TradeStartTime);
datetime stop_time = StringToTime(TradeStopTime);
bool run_today = false;
switch(current_day_of_week)
{
case 0:
run_today = Sunday;
break;
case 1:
run_today = Monday;
break;
case 2:
run_today = Tuesday;
break;
case 3:
run_today = Wednesday;
break;
case 4:
run_today = Thursday;
break;
case 5:
run_today = Friday;
break;
case 6:
run_today = Saturday;
break;
}
bool within_time_range = (current_time >= start_time && current_time <= stop_time);
if(run_today && within_time_range)
{
EAActivated = true;
}
else
{
EAActivated = false;
}
if(!EAActivated)
{
close_buy_position();
CheckAndCancelBuyStopOrders();
CheckAndCancelBuyLimitOrders();
CheckAndCancelSellLimitOrders();
CheckAndCancelSELLStopOrders();
buyupsll=false;
buydownsll=false;
sellupsll=false;
selldownsll=false;
buyuptgt=false;
buydowntgt=false;
selluptgt=false;
selldowntgt=false;
close_sell_position();
runonce = false;
}
ltp=iClose(Symbol(),PERIOD_CURRENT,0);
ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
bid=SymbolInfoDouble(Symbol(),SYMBOL_BID);
Comment(
"\n\nbuylevel: "+buylevel+
"\n\nselllevel: "+selllevel+
"\n\nslcount: "+slcount+
"\n\nTrend: "+Trend+
"\n\nBuy_uptgt: "+Buy_uptgt+
"\n\nBuy_upsll: "+Buy_upsll+
"\n\nsell_uptgt: "+sell_uptgt+
"\n\nsell_upsll: "+sell_upsll+
"\n\nBuy_downtgt: "+Buy_downtgt+
"\n\nBuy_downsll: "+Buy_downsll+
"\n\nsell_downtgt: "+sell_downtgt+
"\n\nsell_downsll: "+sell_downsll
);
if(EAActivated==true&&runonce==true)
{
if(ltp>=buylevel)
{
buylevel=ltp+TradeDist;
selllevel=ltp-TradeDist;
CheckAndCancelBuyLimitOrders();
//CheckAndCancelBuyStopOrders();
CheckAndCancelSELLStopOrders();
// CheckAndCancelSellLimitOrders();
if(InitialTradeTarget>0)
{
Buy_uptgt=buylevel+InitialTradeTarget;
Buy_downtgt=selllevel+InitialTradeTarget;
sell_uptgt=buylevel-InitialTradeTarget;
sell_downtgt=selllevel-InitialTradeTarget;
}
if(InitialTradeSl>0)
{
Buy_upsll=buylevel-InitialTradeSl;
Buy_downsll=selllevel-InitialTradeSl;
sell_upsll=buylevel+InitialTradeSl;
sell_downsll=selllevel+InitialTradeSl;
}
for(int i = 0; i < ArraySize(parts); i++)
{
trade.SetExpertMagicNumber(MagicNumber);
PlaceLimitOrder(Symbol(), buylevel,DoubleToString(parts[i], 2),ORDER_TYPE_BUY_STOP,Buy_upsll, Buy_uptgt);
trade.SetExpertMagicNumber(MagicNumber);
PlaceLimitOrder(Symbol(), selllevel,DoubleToString(parts[i], 2),ORDER_TYPE_SELL_STOP,sell_downsll, sell_downtgt);
}
//sell stop
for(int i = 0; i < ArraySize(parts); i++)
{
trade.SetExpertMagicNumber(MagicNumber);
PlaceLimitOrder(Symbol(), selllevel,DoubleToString(parts[i], 2),ORDER_TYPE_BUY_LIMIT,Buy_downsll, Buy_downtgt);
trade.SetExpertMagicNumber(MagicNumber);
PlaceLimitOrder(Symbol(), buylevel,DoubleToString(parts[i], 2),ORDER_TYPE_SELL_LIMIT, sell_upsll, sell_uptgt);
}
}
if(ltp<=selllevel)
{
buylevel=ltp+TradeDist;
selllevel=ltp-TradeDist;
//CheckAndCancelBuyLimitOrders();
CheckAndCancelBuyStopOrders();
// CheckAndCancelSELLStopOrders();
CheckAndCancelSellLimitOrders();
if(InitialTradeTarget>0)
{
Buy_uptgt=buylevel+InitialTradeTarget;
Buy_downtgt=selllevel+InitialTradeTarget;
sell_uptgt=buylevel-InitialTradeTarget;
sell_downtgt=selllevel-InitialTradeTarget;
}
if(InitialTradeSl>0)
{
Buy_upsll=buylevel-InitialTradeSl;
Buy_downsll=selllevel-InitialTradeSl;
sell_upsll=buylevel+InitialTradeSl;
sell_downsll=selllevel+InitialTradeSl;
}
for(int i = 0; i < ArraySize(parts); i++)
{
trade.SetExpertMagicNumber(MagicNumber);
PlaceLimitOrder(Symbol(), buylevel,DoubleToString(parts[i], 2),ORDER_TYPE_BUY_STOP,Buy_upsll, Buy_uptgt);
trade.SetExpertMagicNumber(MagicNumber);
PlaceLimitOrder(Symbol(), selllevel,DoubleToString(parts[i], 2),ORDER_TYPE_SELL_STOP,sell_downsll, sell_downtgt);
}
//sell stop
for(int i = 0; i < ArraySize(parts); i++)
{
trade.SetExpertMagicNumber(MagicNumber);
PlaceLimitOrder(Symbol(), selllevel,DoubleToString(parts[i], 2),ORDER_TYPE_BUY_LIMIT,Buy_downsll, Buy_downtgt);
trade.SetExpertMagicNumber(MagicNumber);
PlaceLimitOrder(Symbol(), buylevel,DoubleToString(parts[i], 2),ORDER_TYPE_SELL_LIMIT, sell_upsll, sell_uptgt);
}
}
}
////main trades
if(EAActivated==true&&runonce==false)
{
runonce=true;
buylevel=ltp+InitialTradeDist;
selllevel=ltp-InitialTradeDist;
Alert("Initial trades taken @ "+Symbol());
//Buy_uptgt,Buy_upsll,Buy_downtgt,Buy_downsll,sell_uptgt,sell_upsll,sell_downtgt,sell_downsll
if(InitialTradeTarget>0)
{
Buy_uptgt=buylevel+InitialTradeTarget;
Buy_downtgt=selllevel+InitialTradeTarget;
sell_uptgt=buylevel-InitialTradeTarget;
sell_downtgt=selllevel-InitialTradeTarget;
}
if(InitialTradeSl>0)
{
Buy_upsll=buylevel-InitialTradeSl;
Buy_downsll=selllevel-InitialTradeSl;
sell_upsll=buylevel+InitialTradeSl;
sell_downsll=selllevel+InitialTradeSl;
}
//buy stop
for(int i = 0; i < ArraySize(parts); i++)
{
trade.SetExpertMagicNumber(MagicNumber);
PlaceLimitOrder(Symbol(), buylevel,DoubleToString(parts[i], 2),ORDER_TYPE_BUY_STOP,Buy_upsll, Buy_uptgt);
trade.SetExpertMagicNumber(MagicNumber);
PlaceLimitOrder(Symbol(), selllevel,DoubleToString(parts[i], 2),ORDER_TYPE_SELL_STOP,sell_downsll, sell_downtgt);
}
//sell stop
for(int i = 0; i < ArraySize(parts); i++)
{
trade.SetExpertMagicNumber(MagicNumber);
PlaceLimitOrder(Symbol(), selllevel,DoubleToString(parts[i], 2),ORDER_TYPE_BUY_LIMIT,Buy_downsll, Buy_downtgt);
trade.SetExpertMagicNumber(MagicNumber);
PlaceLimitOrder(Symbol(), buylevel,DoubleToString(parts[i], 2),ORDER_TYPE_SELL_LIMIT, sell_upsll, sell_uptgt);
}
buyupsll=false;
buydownsll=false;
sellupsll=false;
selldownsll=false;
buyuptgt=false;
buydowntgt=false;
selluptgt=false;
selldowntgt=false;
}
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
void close_sell_position()
{
for(int i=PositionsTotal()-1; i>=0; i--)
{
string currencypair=PositionGetSymbol(i);
int position_direction=PositionGetInteger(POSITION_TYPE);
int posmagic=PositionGetInteger(POSITION_MAGIC);
// Alert("posmagic: "+posmagic);
// Alert("MagicNumber: "+MagicNumber);
// Alert("position_direction: "+position_direction);
if(currencypair==Symbol() && position_direction == POSITION_TYPE_SELL&& int(posmagic) == int(MagicNumber))
{
// Alert("MagicNumber: reaching");
ulong ticket=PositionGetTicket(i);
trade.PositionClose(ticket);
}
}
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void close_buy_position()
{
for(int i=PositionsTotal()-1; i>=0; i--)
{
string currencypair=PositionGetSymbol(i);
int position_direction=PositionGetInteger(POSITION_TYPE);
int posmagic=PositionGetInteger(POSITION_MAGIC);
// Alert("posmagic: "+posmagic);
// Alert("MagicNumber: "+MagicNumber);
// Alert("position_direction: "+position_direction);
if(currencypair==Symbol() && position_direction == POSITION_TYPE_BUY && int(posmagic) == int(MagicNumber)
)
{
// Alert("MagicNumber: reaching");
ulong ticket=PositionGetTicket(i);
trade.PositionClose(ticket);
}
}
}
//+------------------------------------------------------------------+
void PlaceLimitOrder(string symbol,double price,double volume,ENUM_ORDER_TYPE orderType,double sl = 0,double tp = 0,datetime expiration = 0)
{
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
request.action = TRADE_ACTION_PENDING; // For limit orders, use pending action
request.symbol = symbol; // The symbol to trade, e.g., "EURUSD"
request.volume = volume; // Lot size
request.type = orderType; // Order type (e.g., ORDER_TYPE_BUY_LIMIT or ORDER_TYPE_SELL_LIMIT)
request.price = price; // The price at which the order will be executed
request.sl = sl; // Stop Loss price
request.tp = tp; // Take Profit price
request.deviation = 10; // Max price deviation in pips
request.expiration = expiration; // Set expiration if needed
request.magic = MagicNumber; // Identifier for the order
request.comment = "Limit Order with SL and TP";
if(OrderSend(request, result))
{
Print("Limit order placed successfully. Order ticket: ", result.order);
}
else
{
Print("Failed to place limit order. Error: ", GetLastError());
}
}
//+------------------------------------------------------------------+
void CheckAndCancelBuyStopOrders()
{
string chartSymbol = _Symbol; // Get the current chart symbol
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
ulong orderTicket = OrderGetTicket(i); // Get the ticket number of the order
if(orderTicket > 0)
{
string orderSymbol = OrderGetString(ORDER_SYMBOL);
ENUM_ORDER_TYPE orderType = ENUM_ORDER_TYPE(OrderGetInteger(ORDER_TYPE));
if(orderSymbol == chartSymbol && orderType == ORDER_TYPE_BUY_STOP)
{
bool result = trade.OrderDelete(orderTicket); // Attempt to cancel the order
if(result)
{
Print("Buy Stop order ", orderTicket, " on ", orderSymbol, " has been successfully canceled.");
}
else
{
Print("Failed to cancel Buy Stop order ", orderTicket, ", error code: ", GetLastError());
}
}
}
else
{
Print("Failed to get order ticket for index ", i, ", error code: ", GetLastError());
}
}
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void CheckAndCancelSELLStopOrders()
{
string chartSymbol = _Symbol;
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
ulong orderTicket = OrderGetTicket(i);
if(orderTicket > 0)
{
string orderSymbol = OrderGetString(ORDER_SYMBOL);
ENUM_ORDER_TYPE orderType = ENUM_ORDER_TYPE(OrderGetInteger(ORDER_TYPE));
if(orderSymbol == chartSymbol && orderType == ORDER_TYPE_SELL_STOP)
{
bool result = trade.OrderDelete(orderTicket);
if(result)
{
Print("Sell Stop order ", orderTicket, " on ", orderSymbol, " has been successfully canceled.");
}
else
{
Print("Failed to cancel Sell Stop order ", orderTicket, ", error code: ", GetLastError());
}
}
}
else
{
Print("Failed to get order ticket for index ", i, ", error code: ", GetLastError());
}
}
}
//+------------------------------------------------------------------+
void CheckAndCancelSellLimitOrders()
{
string chartSymbol = _Symbol; // Get the current chart symbol
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
ulong orderTicket = OrderGetTicket(i); // Get the ticket number of the order
if(orderTicket > 0)
{
string orderSymbol = OrderGetString(ORDER_SYMBOL);
ENUM_ORDER_TYPE orderType = ENUM_ORDER_TYPE(OrderGetInteger(ORDER_TYPE));
if(orderSymbol == chartSymbol && orderType == ORDER_TYPE_SELL_LIMIT)
{
bool result = trade.OrderDelete(orderTicket); // Attempt to cancel the order
if(result)
{
Print("Sell Limit order ", orderTicket, " on ", orderSymbol, " has been successfully canceled.");
}
else
{
Print("Failed to cancel Sell Limit order ", orderTicket, ", error code: ", GetLastError());
}
}
}
else
{
Print("Failed to get order ticket for index ", i, ", error code: ", GetLastError());
}
}
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void CheckAndCancelBuyLimitOrders()
{
string chartSymbol = _Symbol; // Get the current chart symbol
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
ulong orderTicket = OrderGetTicket(i); // Get the ticket number of the order
if(orderTicket > 0)
{
string orderSymbol = OrderGetString(ORDER_SYMBOL);
ENUM_ORDER_TYPE orderType = ENUM_ORDER_TYPE(OrderGetInteger(ORDER_TYPE));
if(orderSymbol == chartSymbol && orderType == ORDER_TYPE_BUY_LIMIT)
{
bool result = trade.OrderDelete(orderTicket); // Attempt to cancel the order
if(result)
{
Print("Buy Limit order ", orderTicket, " on ", orderSymbol, " has been successfully canceled.");
}
else
{
Print("Failed to cancel Buy Limit order ", orderTicket, ", error code: ", GetLastError());
}
}
}
else
{
Print("Failed to get order ticket for index ", i, ", error code: ", GetLastError());
}
}
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
void lastclosedorder()
{
uint TotalNumberOfDeal = HistoryDealsTotal();
ulong Ticket = 0;
long OrderType, DealEntry, Reason;
string MySymbol = "";
double price = 0, stoploss = 0, target = 0;
double ltp = iClose(Symbol(), PERIOD_CURRENT, 0); // Last tick price or market price
// Persistent static array to store processed tickets
static ulong ProcessedTickets[];
static int ProcessedTicketsCount = 0;
HistorySelect(0, TimeCurrent()); // Select the history for the current time range
for(uint i = 0; i < TotalNumberOfDeal; i++)
{
// Get the ticket ID
if((Ticket = HistoryDealGetTicket(i)) > 0)
{
// Check if this ticket has already been processed
if(IsTicketProcessed(Ticket, ProcessedTickets, ProcessedTicketsCount))
continue; // Skip this ticket if already processed
// Retrieve deal information
OrderType = HistoryDealGetInteger(Ticket, DEAL_TYPE);
MySymbol = HistoryDealGetString(Ticket, DEAL_SYMBOL);
DealEntry = HistoryDealGetInteger(Ticket, DEAL_ENTRY);
Reason = HistoryDealGetInteger(Ticket, DEAL_REASON);
// price = HistoryDealGetDouble(Ticket, DEAL_PRICE);
stoploss = HistoryDealGetDouble(Ticket, DEAL_SL);
target = HistoryDealGetDouble(Ticket, DEAL_TP);
long magic_number = HistoryOrderGetInteger(Ticket, ORDER_MAGIC);
// Check if this deal matches the current symbol and is an exit deal
if(MySymbol == Symbol() && DealEntry == DEAL_ENTRY_OUT&&int(magic_number)==int(MagicNumber))
{
printf("OrderType: " + IntegerToString(OrderType) +
" MySymbol: " + MySymbol +
" DealEntry: " + IntegerToString(DealEntry) +
" Reason: " + IntegerToString(Reason)+
" price: " + IntegerToString(price)+
" stoploss: " + IntegerToString(stoploss)+
" target: " + IntegerToString(target));
if(Reason == 4 && OrderType == 1)
{
price = stoploss+InitialTradeSl;
if(ltp < price)
{
for(int i = 0; i < ArraySize(parts); i++)
{
trade.SetExpertMagicNumber(MagicNumber);
PlaceLimitOrder(Symbol(), price,DoubleToString(parts[i], 2),ORDER_TYPE_BUY_STOP,stoploss, target);
}
}
if(ltp > price)
{
for(int i = 0; i < ArraySize(parts); i++)
{
trade.SetExpertMagicNumber(MagicNumber);
PlaceLimitOrder(Symbol(), price,DoubleToString(parts[i], 2),ORDER_TYPE_BUY_LIMIT,stoploss, target);
}
}
}
if(Reason == 4 && OrderType == 0)
{
price = stoploss-InitialTradeSl;
if(ltp < price)
{
for(int i = 0; i < ArraySize(parts); i++)
{
trade.SetExpertMagicNumber(MagicNumber);
PlaceLimitOrder(Symbol(), price,DoubleToString(parts[i], 2),ORDER_TYPE_SELL_LIMIT,stoploss, target);
}
}
if(ltp > price)
{
for(int i = 0; i < ArraySize(parts); i++)
{
trade.SetExpertMagicNumber(MagicNumber);
PlaceLimitOrder(Symbol(), price,DoubleToString(parts[i], 2),ORDER_TYPE_SELL_STOP,stoploss, target);
}
}
}
}
// Mark this ticket as processed
ArrayResize(ProcessedTickets, ProcessedTicketsCount + 1);
ProcessedTickets[ProcessedTicketsCount++] = Ticket;
}
}
}
// Function to check if a ticket is already processed
bool IsTicketProcessed(ulong ticket, ulong &processedTickets[], int processedCount)
{
for(int i = 0; i < processedCount; i++)
{
if(processedTickets[i] == ticket)
return true; // Ticket already processed
}
return false;
}
// Function to check all closed orders and print their details
/*void lastclosedorder()
{
uint TotalNumberOfDeal=HistoryDealsTotal();
ulong Ticket=0;
long OrderType,DealEntry,Reason;
string MySymbol="";
string PosDirection="";
double price=0;
HistorySelect(0,TimeCurrent());
for(uint i=0;i<TotalNumberOfDeal;i++)
{
if((Ticket=HistoryDealGetTicket(i))>0)
{
OrderType=HistoryDealGetInteger(Ticket,DEAL_TYPE);
MySymbol=HistoryDealGetString(Ticket,DEAL_SYMBOL);
DealEntry=HistoryDealGetInteger(Ticket,DEAL_ENTRY);
Reason=HistoryDealGetInteger(Ticket,DEAL_REASON);
price=HistoryDealGetDouble(Ticket,DEAL_PRICE);
stoploss=HistoryDealGetDouble(Ticket,DEAL_SL);
target=HistoryDealGetDouble(Ticket,DEAL_TP);
if(MySymbol==Symbol())
{
if(DealEntry==DEAL_ENTRY_OUT)
{
printf("OrderType: "+OrderType+" MySymbol: "+MySymbol+" DealEntry: "+DealEntry+" Reason: "+Reason);
if(Reason==4&&OrderType==1)
{
if(ltp<price)
{
}
if(ltp>price)
{
}
}
}
}
}
}
}*/
//+------------------------------------------------------------------+
Comments
Post a Comment