class BackEndStrategy {
private:
CTrade trade;
double accountBalance;
double equity;
double thresholdLossPercent;
string symbol;
double pipSize;
int direction; // 0 for buy, 1 for sell
double lotSize;
double initialSpotPrice;
double furthestOpenPositionPrice;
// Additional attributes as needed for managing grid and orders
public:
// Constructor to initialize the strategy
BackEndStrategy(string symbolInit, double pipSizeInit, double thresholdLossPercentInit, double lotSizeInit) {
symbol = symbolInit;
pipSize = pipSizeInit;
thresholdLossPercent = thresholdLossPercentInit;
lotSize = lotSizeInit;
// Initialize other attributes as necessary
}
code
// Method to evaluate and activate the BE strategy
void EvaluateAndActivate();
// Method to close profitable positions
void CloseProfitablePositions();
// Method to backfill the dead zone with opposite pending orders
void BackfillDeadZone();
// Method to close losing positions to balance the profits
void CloseLosingPositions();
// Additional methods as needed for strategy execution
};
class _Grid
{
code
public:
int _gridlevels;
int _gridpipsize;
double _grid_data[];
ulong _grid_ticket[];
double proffit[];
int _grid_type[];
double _lotts[];
double _pip;
string _symbol;
int _symbol_int;
int _dir;
double _pipval;
double _lots;
public:
void _Grid(string, int, double, int, int); //constructor
void _create_grid(void); //place initial orders and constructs price grid
void _close_pair(void); //closes all positions on a pair
void _eval_grid(void);
void _tickets(void);
void _reposition(void);
int _boundary(void);
void _close_winners(void);
void _close_losers(void);
void _close_all_by_book(void);
bool _grid_check(void);
void _create_single_order(int);
Assistant
};
class MarketSessionChecker
{
private:
string symbol; // Symbol to check market session for
code
public:
// Constructor to set the symbol
void MarketSessionChecker(string symbolName);
bool IsMarketOpen();
//input double _loss=0.019;
double _price1;
double _price2;
double _price3;
int flag1=0;
int flag2=0;
int flag3=0;
string Symbol1="EURJPY";
string Symbol2="EURUSD";
string Symbol3="USDJPY";
int grudlevels=_gridlevels;
_Grid Grid1("EURJPY", 0, _pipval, grudlevels, 1);
_Grid Grid2("EURUSD", 1, _pipval, grudlevels, 1);
_Grid Grid3("USDJPY", 1, _pipval, grudlevels, 1);
//input string activationFilePath = "C:\Path\To\Activation\File.txt"; // Path to the activation file
//input string activationKey = "YourActivationKey"; // Your predefined activation key
//datetime deactivateTime; // Time of deactivation
int OnInit()
{
//deactivateTime = GetDeactivationTime(); // Set the deactivation time to Friday at 5 PM CST
//EventSetTimer(3600); // Set a timer to check every hour
double effectiveBalance = AccountInfoDouble(ACCOUNT_BALANCE); //* tradingPercentage;
double pipValue = 0.1; // Default starting pip value
code
// Adjust pip value based on the effective balance
if (effectiveBalance > 100000) {
int extraTens = (effectiveBalance - 100000) / 10000;
pipValue += extraTens * 0.1;
}
// Initialize Grid objects with the calculated pip value
Grid1 = _Grid("EURJPY", 0, pipValue, _gridlevels, 1);
Grid2 = _Grid("EURUSD", 1, pipValue, _gridlevels, 1);
Grid3 = _Grid("USDJPY", 1, pipValue, _gridlevels, 1);
// Initialize prices
_price1 = NormalizeDouble(SymbolInfoDouble(Symbol1, SYMBOL_ASK), _Digits);
_price2 = NormalizeDouble(SymbolInfoDouble(Symbol2, SYMBOL_BID), _Digits);
_price3 = NormalizeDouble(SymbolInfoDouble(Symbol3, SYMBOL_BID), _Digits);
// Create grids in a rotating manner
for(int level = 0; level < _gridlevels; level++) {
if(sessionChecker1.IsMarketOpen() && sessionChecker2.IsMarketOpen() && sessionChecker3.IsMarketOpen()) {
// Market is open, place trades here
Grid1._create_single_order(level);
Grid2._create_single_order(level);
Grid3._create_single_order(level);
} else {
Print("Market is not open for trading.");
}
}
// Get tickets for each grid
Grid1._tickets();
Grid2._tickets();
Grid3._tickets();
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
/*void OnTick()
{
//--- // Check if current time is past the deactivation time
//if (TimeCurrent() >= deactivateTime)
//{
// Check if the activation file contains the correct key
// if (!IsActivated())
// {
// Print("This .ex5 file has been deactivated.");
// ExpertRemove(); // Stop the Expert Advisor
//}
// }
double balans=AccountInfoDouble(ACCOUNT_BALANCE);
double eqquity=AccountInfoDouble(ACCOUNT_EQUITY);
_price1=NormalizeDouble(SymbolInfoDouble(Symbol1,SYMBOL_ASK),_Digits);
_price2=NormalizeDouble(SymbolInfoDouble(Symbol2,SYMBOL_BID),_Digits);
_price3=NormalizeDouble(SymbolInfoDouble(Symbol3,SYMBOL_BID),_Digits);
code
if(eqquity-balans>=balans*(_percent_win))
{
Grid1._close_pair();
Grid2._close_pair();
Grid3._close_pair();
for(int level = 0; level < _gridlevels; level++) {
if(sessionChecker1.IsMarketOpen() && sessionChecker2.IsMarketOpen() && sessionChecker3.IsMarketOpen()) {
// Market is open, place trades here
Grid1._create_single_order(level);
Grid2._create_single_order(level);
Grid3._create_single_order(level);
} else {
Print("Market is not open for trading.");
return;
}
}
Grid1._tickets();
Grid2._tickets();
Grid3._tickets();
}
// Function to check if the .ex5 file is activated
/*bool IsActivated()
{
string fileData;
int fileHandle = FileOpen(activationFilePath, FILE_READ | FILE_ANSI);
if (fileHandle != INVALID_HANDLE)
{
// Read the file content
FileReadString(fileHandle, fileData);
FileClose(fileHandle);
code
// Check if the file content matches the activation key
return StringCompare(fileData, activationKey) == 0;
}
return false;
}
// Function to calculate the next deactivation time
datetime GetDeactivationTime()
{
datetime currentTime = TimeCurrent();
MqlDateTime mqlTime;
TimeToStruct(currentTime, mqlTime);
code
// Adjust for CST (UTC-6), adapt daylight saving time if necessary
int cstOffset = 6 * 3600;
datetime cstTime = currentTime - cstOffset;
// Find the next Friday 5 PM
while (mqlTime.day_of_week != 5 || mqlTime.hour != 17)
{
cstTime += 3600; // Increment by one hour
TimeToStruct(cstTime, mqlTime);
}
return cstTime + cstOffset; // Convert back to server time
}
*/
void _Grid::_Grid(string symbol, int dir, double pipval, int gridlevels, int gridpipsize)
{
void _Grid::_close_pair(void)
{
// Correctly declare the ticketNumbers array
long ticketNumbers[];
ArrayResize(ticketNumbers, PositionsTotal());
code
// Delete pending orders for the specified symbol
int totalOrders = OrdersTotal();
for (int i = totalOrders - 1; i >= 0; i--) {
ulong ticket = OrderGetTicket(i);
// Select the order by its ticket number
if (OrderSelect(ticket)) {
string orderSymbol = OrderGetString(ORDER_SYMBOL);
ENUM_ORDER_TYPE type = (ENUM_ORDER_TYPE)OrderGetInteger(ORDER_TYPE);
if (orderSymbol == _symbol) {
switch (type) {
case ORDER_TYPE_BUY_LIMIT:
case ORDER_TYPE_BUY_STOP:
case ORDER_TYPE_SELL_LIMIT:
case ORDER_TYPE_SELL_STOP:
// Delete the order if it's a pending order type
trader.OrderDelete(ticket);
break;
}
}
}
}
// Close positions in FIFO order
int ticketIndex = 0;
// Collect all position tickets for the specified symbol
for(int j = 0; j < PositionsTotal(); j++)
{
ulong posTicket = PositionGetTicket(j);
if (PositionSelect(posTicket)) {
string posSymbol = PositionGetString(POSITION_SYMBOL);
if (posSymbol == _symbol) {
ticketNumbers[ticketIndex++] = posTicket;
}
}
}
// Sort the tickets to ensure FIFO order (ascending order of ticket numbers)
ArraySort(ticketNumbers);
// Close positions in FIFO order
for(int k = 0; k < ticketIndex; k++)
{
ulong ticketToClose = ticketNumbers[k];
if(!trader.PositionClose(ticketToClose))
{
Print("Error closing position with ticket ", ticketToClose, ": ", GetLastError());
}
}
// Reset grid data after closing positions
ArrayInitialize(_grid_data, 0);
ArrayInitialize(_grid_ticket, 0);
double thresholdLoss = accountBalance * thresholdLossPercent; // 8% of account balance
// Placeholder for spot price check against the furthest open position
// This requires fetching the current price and comparing it to the grid's furthest position prices
double currentPrice = SymbolInfoDouble(symbol, SYMBOL_BID); // Assuming bid for sell, use SYMBOL_ASK for buy
// Check if the unrealized loss exceeds the threshold and if the current spot price is beyond the furthest position
if (unrealizedLoss >= thresholdLoss) {
CloseProfitablePositions();
BackfillDeadZone();
CloseLosingPositions();
}
}
/*void BackEndStrategy::CloseProfitablePositions() {
// Reality-bending logic to close profitable positions; specifics depend on not breaking the universe
for (int i = 0; i < PositionsTotal(); ++i) {
string posSymbol = PositionGetSymbol(i); // MQL5 style, Morty!
if (posSymbol == symbol) {
if (PositionSelect(posSymbol)) { // Select the position by symbol, not index, Morty!
double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
double currentPrice = SymbolInfoDouble(symbol, SYMBOL_BID); // Or SYMBOL_ASK for those optimistic buy positions
double profit = PositionGetDouble(POSITION_PROFIT);
ulong ticket = PositionGetInteger(POSITION_TICKET); // Get the ticket for the current position, not some interdimensional index
code
if (profit > 0) {
trade.PositionClose(ticket); // Close it down, Morty, we're in profit!
}
}
}
}
}
*/
void BackEndStrategy::CloseProfitablePositions() {
// Reality-bending logic to close profitable positions; specifics depend on not breaking the universe
for (int i = 0; i < PositionsTotal(); ++i) {
string posSymbol = PositionGetSymbol(i); // MQL5 style, Morty!
if (posSymbol == symbol) {
if (PositionSelect(posSymbol)) { // Select the position by symbol, not index, Morty!
double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
double currentPrice = SymbolInfoDouble(symbol, SYMBOL_BID); // Or SYMBOL_ASK for those optimistic buy positions
double profit = PositionGetDouble(POSITION_PROFIT);
ulong ticket = PositionGetInteger(POSITION_TICKET); // Get the ticket for the current position, not some interdimensional index
code
if (profit > 0) {
trade.PositionClose(ticket); // Close it down, Morty, we're in profit!
}
}
}
}
}
void BackEndStrategy::BackfillDeadZone() {
// Assuming we have a mechanism to determine the dead zone's boundaries
double startPrice = furthestOpenPositionPrice; // This needs to be dynamically determined
double endPrice = initialSpotPrice; // This also needs to be dynamically determined
code
// Determine the direction for the new orders
int oppositeDirection = direction == 0 ? 1 : 0;
// Place new orders to backfill the dead zone
for (double price = startPrice; price <= endPrice; price += pipSize) {
if (oppositeDirection == 0) {
// Place buy stop for a buy grid
trader.BuyStop(lotSize, price, symbol, 0, 0, 0, 0, "");
} else {
// Place sell stop for a sell grid
trader.SellStop(lotSize, price, symbol, 0, 0, 0, 0, "");
}
}
}
void BackEndStrategy::CloseLosingPositions() {
// Adjusted for the MQL5 reality
double totalClosedProfit = 0; // Calculate this during CloseProfitablePositions
double totalClosedLoss = 0;
code
for (int i = 0; i < PositionsTotal(); ++i) {
string posSymbol = PositionGetSymbol(i); // MQL5 style, grabbing the symbol directly
if (posSymbol == symbol) {
if (PositionSelect(posSymbol)) { // Select the position by its symbol
double loss = PositionGetDouble(POSITION_PROFIT);
ulong ticket = PositionGetInteger(POSITION_TICKET); // Correct MQL5 function to get the ticket
if (loss < 0 && totalClosedLoss < totalClosedProfit) {
trade.PositionClose(ticket); // Close the position based on the ticket
totalClosedLoss += loss; // Update the total closed loss
}
}
}
}
// Keep in mind, balancing profits and losses is an art and a science, Morty
}
The code you've provided is written in MQL5, which is the programming language used to automate trading strategies on the MetaTrader platform. The code snippet defines several classes and functions aiming to implement a complex trading strategy that involves multiple currency pairs (EURJPY, EURUSD, and USDJPY), order grid systems, and backend strategies that execute when certain conditions are met. The code also features placeholders and commented sections, indicating that it's either under construction or designed for further customization.
Here's a breakdown of what the various components of the code are intended to do:
BackEndStrategy class: This class is designed to handle what appears to be a "safety net" strategy that activates under specific conditions of loss. It includes methods to evaluate activation conditions (EvaluateAndActivate), close profitable positions (CloseProfitablePositions), fill a "dead zone" with opposite pending orders (BackfillDeadZone), and close losing positions in an attempt to balance profits (CloseLosingPositions).
_Grid class: This class is meant to manage a grid trading system. A grid system places orders at regular intervals above and below a set price. The functions in this class are meant to create this grid (_create_grid), close all positions (_close_pair), evaluate the grid (_eval_grid), and do various grid-related operations.
MarketSessionChecker class: This class contains functions to check whether the market is open for a given symbol (IsMarketOpen).
Global instances of BackEndStrategy and MarketSessionChecker for each symbol (EURJPY, EURUSD, USDJPY) are created to manage trading strategies and session checks for each currency pair.
The OnInit function: This is called when the Expert Advisor (EA) starts. It initializes the balance, pip value, creates order grids, and sets up the initial conditions for trading.
The OnTick function: This function is called every time there is a new price update ("tick"). It manages the backend strategy's evaluation, order grid creation, and handles position closures based on equity conditions.
The MarketSessionChecker class is used within the OnTick function to ensure the market is open before placing orders with the grid system.
The _Grid class's _create_single_order method is used to place individual orders for the grid system at predetermined levels.
Some commented out sections involve deactivation measures, potentially aimed at stopping the EA based on time or an external "activation file". This could be for security or licensing purposes.
There are a number of utility and helper functions to aid in order and ticket management.
Overall, the code is complex and seems to be part of an advanced trading system that trades multiple currency pairs using a grid system and employs a backend strategy to limit losses and manage orders based on market conditions. It's important to note that trading involves risk, and automated strategies must be thoroughly tested and used with caution.