Files
xMQL5/MQLTestWorkspace/BKPS/BKP/EquityManagementOld.mq5
T
2024-04-27 01:16:17 +03:30

988 lines
25 KiB
Plaintext

//
// Check All Open Positions and it's Supports ...
void HandleSupportHedgeGuard()
{
//
// We Have two different Senario ...
// 1- Hedge a Position by it's Supprots ...
// 2- Hedge Whole Positions ...
//
double minSupportVolume = 0.01;
double minRequiredProfitPerEachTradeForHedging = 0.2;
//
// Check Open Positions ...
int positionsCount = mTrader.CountPositions();
if (positionsCount <= 0)
{
return;
}
//
// Define Profit Summary Variable ...
double profitSummary = 0;
//
// Retrieve Open Positions ...
XPosition positions[];
mTrader.GetPositions(positions);
//
// Try to Detect Each Position by it's Supports ...
for (int i = 0; i < positionsCount; i++)
{
//
// Retrieve Indexed Position ...
XPosition iPosition = positions[i];
//
// Define Profit Summary Variable ...
profitSummary = iPosition.profit;
//
XPositionPack pack;
bool hasPack = mTrader.GetPositionPack(
iPosition.ticket,
pack);
if (!hasPack)
{
continue;
}
//
// Check Position's Supports is Executed or Not ...
bool isSupportOpen = pack.supportPositionsCount > 0;
if (!isSupportOpen)
{
//
// Here we must Check to Do Additional Support ...
//
continue;
}
//
// Check Profit Summary ...
for (int j = 0; j < pack.supportPositionsCount; j++)
{
//
XPosition jPosition = pack.supportPositions[j];
//
profitSummary += jPosition.profit;
}
//
// Now se Decide What to do based On Profit Summary ...
if (profitSummary > 0)
{
//
// Close and Hedge ...
CancelSupport(
pack,
true);
}
else if (profitSummary < 0)
{
//
// Do Additional Supports ...
}
}
//
// Check Conditions for All Hedge Senario ...
profitSummary = 0;
double requiredProfit = 0;
for (int i = 0; i < positionsCount; i++)
{
//
XPosition iPosition = positions[i];
//
requiredProfit += (minRequiredProfitPerEachTradeForHedging * (iPosition.volume / minSupportVolume)) + (-1 * iPosition.swap);
profitSummary += iPosition.profit;
}
//
// Check Closing Condition ...
bool isProfitPassedForHedge = (profitSummary > requiredProfit);
if (!isProfitPassedForHedge)
{
return;
}
//
string comment = "EQM Close ...";
int closed = mTrader.ClosePositions(
positions,
comment);
//
if (closed > 0)
{
//
string message = "In Profit Hedge using Equity Manager by Profit: " + ToString(profitSummary);
//
LogMessage(message);
}
}
//
// When Equity is Locked but Support Positions doesn't
// Triggered ...
void HandleEquitySupportGuard()
{
//
// Add theme on Coonfigs ...
int reuiredAge = 35;
//
bool hasEquity = CheckEquityForTrade();
if (hasEquity)
{
//
// TODO:
// Here We Can Close All Exists Support Signals if their
// related Positions was Gone ...
return;
}
//
// Retrieve in DrawDown Positions ...
XPosition positions[];
GetInDrawdownPositions(
positions);
int positionsCount = ArraySize(positions);
if (positionsCount <= 0)
{
return;
}
//
for (int i = 0; i < positionsCount; i++)
{
//
XPosition iPosition = positions[i];
//
XPositionPack iPack;
bool hasPack = mTrader.GetPositionPack(
iPosition.ticket,
iPack);
if (!hasPack || iPack.supportOrdersCount <= 0)
{
//
// Here We Have to Check if Added before or not ...
int supIdx = GetSupportsIndex(iPosition.ticket);
if (supIdx < 0)
{
//
XSupport support;
//
support.position = iPosition;
support.lastSupportVolume = iPosition.volume;
support.lastSupport = TimeToMilliSeconds(iPosition.openAt);
//
AddSupports(support);
//
supIdx = GetSupportsIndex(iPosition.ticket);
}
//
int supportAge = GetSupportAge(supIdx);
bool isSupportAgePassed = supportAge > reuiredAge;
if (!isSupportAgePassed)
{
continue;
}
//
XSignal supports[];
bool isGenerated = GenerateSupportSignals(
iPosition,
supports,
mSupports[supIdx].lastSupportVolume * 2);
if (!isGenerated)
{
continue;
}
//
// Try to Execute New Support Signals ...
bool isExecuted = ExecuteSupportSignals(
iPosition,
supports);
if (isExecuted)
{
//
// Update Support ...
datetime barTime = iTime(
iPosition.symbol,
iPosition.period,
0);
mSupports[supIdx].position = iPosition;
mSupports[supIdx].lastSupportVolume *= 2;
mSupports[supIdx].lastSupport = TimeToMilliSeconds(barTime);
//
// string message = "Position (" + ToString(iPosition.ticket) + ") Close Due Equity Manager ...";
string message = "Cancel Position (" + ToString(iPosition.ticket) + ") Supports and Provide New Supports for Equity Management ...";
//
LogMessage(message);
}
//
continue;
}
//
// Calculate Support Order Age ...
int longAge = 0;
for (int j = 0; j < iPack.supportOrdersCount; j++)
{
//
XOrder jOrder = iPack.supportOrders[j];
//
int jAge = GetOrderAge(
jOrder,
iPosition.period);
//
if (longAge == 0 || longAge < jAge)
{
longAge = jAge;
}
}
//
// Check Longest Oreder Age is Passed Required Age or not ...
bool hasLongAgeSupport = longAge >= reuiredAge;
if (!hasLongAgeSupport)
{
continue;
}
//
// now we Have to Cancel all Supports ...
bool isCancelSupports = CancelSupport(
iPack);
if (!isCancelSupports)
{
continue;
}
//
XSignal supports[];
bool isGenerated = GenerateSupportSignals(
iPack.position,
supports);
if (!isGenerated)
{
continue;
}
//
// Try to Execute New Support Signals ...
bool isExecuted = ExecuteSupportSignals(
iPack.position,
supports);
if (isExecuted)
{
//
string message = "Cancel Position (" + ToString(iPack.ticket) + ") Supports and Provide New Supports for Equity Management ...";
//
LogMessage(message);
}
}
}
//
// if (result)
// {
// //
// bool hasEquity = CheckEquityForTrade();
// if (!hasEquity)
// {
// //
// // TODO:
// // Here we can check MaxIn Drawdown Position Type and
// // ignore Indirection Positions if it's Only One Trade Open ...
// // since Base EA Class ignore this Case and doesn't do anything, since
// // it's a Custom Senario ...
// // We have to implement it manually ...
// // PickEquityManagerSignal(signals);
// }
// }
//
void PickEquityManagerSignal(XSignal &signals[])
{
//
// Check Equity ...
bool hasEquity = CheckEquityForTrade();
if (hasEquity)
{
return;
}
//
// Check Singals Count ...
int signalsCount = ArraySize(signals);
if (signalsCount <= 0)
{
return;
}
//
// Retrieve Provider Count ...
int providersCount = ArraySize(mProviders);
if (providersCount <= 0)
{
return;
}
//
// Loop Through Registered Provider Instances ...
for (int i = 0; i < providersCount; i++)
{
//
X121SignalProvider iSProvider = mProviders[i];
//
string symbol = iSProvider.symbol;
ENUM_TIMEFRAMES period = iSProvider.period;
//
// Now we Have to Retrieve In Darwdown Position ...
XPosition inDrawDownPositions[];
GetInDrawdownPositions(
inDrawDownPositions,
symbol,
NULL, // All Types Of Positions ...
period,
NULL, // All Types Of Signal Providers ...
X_POSITION_SELECT_MAX // Max Positions Select ...
);
int inDrawDownPositionsCount = ArraySize(inDrawDownPositions);
if (inDrawDownPositionsCount <= 0)
{
continue;
}
//
// Since we Select Max Method and then Validate count, there was at least one it ...
// which is the max ...
ENUM_POSITION_TYPE type = inDrawDownPositions[0].type;
//
// Now we have to Loop Through Provided Signals which
// relate to Indirection type of in drawdown position,
// then simplely we can Execute it ...
for (int j = 0; j < signalsCount; j++)
{
//
XSignal jSignal = signals[j];
//
// Check Signal is belong to this provider ...
if (jSignal.symbol != iSProvider.symbol ||
jSignal.period != iSProvider.period)
{
continue;
}
//
// we have sure the signal is belongs to current provider ...
// Check signal direction ...
// also we Check Signal Execution mode is MARKET mode ...
if (jSignal.type == type || jSignal.mode != X_ORDER_MODE_MARKET)
{
continue;
}
//
// Do Signal Preparation ...
PrepareSignal(jSignal);
//
// Now we can Execute Signal ...
bool isExecuted = mTrader.ExecuteSignal(jSignal);
if (isExecuted)
{
break;
}
}
}
}
//
//
void HandleEquityManagement()
{
//
// TODO: add this to Configurations ...
int longAgeDetection = 35;
double supportVolumeMultiplier = 2;
//
// Check Equity ...
bool hasEquity = CheckEquityForTrade();
if (hasEquity)
{
return;
}
//
// Retrieve Provider Count ...
int providersCount = ArraySize(mProviders);
if (providersCount <= 0)
{
return;
}
//
// Loop Through Registered Provider Instances ...
for (int i = 0; i < providersCount; i++)
{
//
X121SignalProvider iSProvider = mProviders[i];
//
string symbol = iSProvider.symbol;
ENUM_TIMEFRAMES period = iSProvider.period;
XSCX121Provider *analyzer = iSProvider.provider;
//
// Now we Have to Retrieve In Darwdown Position ...
XPosition inDrawDownPositions[];
GetInDrawdownPositions(
inDrawDownPositions,
symbol,
NULL, // All Types Of Positions ...
period,
NULL, // All Types Of Signal Providers ...
NULL // All Positions Select ...
);
int inDrawDownPositionsCount = ArraySize(inDrawDownPositions);
if (inDrawDownPositionsCount <= 0)
{
continue;
}
//
// Loop throuigh Positions ...
for (int j = 0; j < inDrawDownPositionsCount; j++)
{
//
// Select Index Model ...
XPosition jPosition = inDrawDownPositions[j];
//
// Check Position is Signal Type or Support Position ...
string jParams[];
bool isSupport = ExtractSupportParams(
jPosition.comment,
jParams);
if (!isSupport)
{
//
// there was some case which a Position still Open in Drawdown
// and it's supports close due take profit ...
// in this case we can simply make sure there isn't any ...
XPositionPack jPack;
bool hasPack = mTrader.GetPositionPack(
jPosition.ticket,
jPack);
if (hasPack && jPack.supportOrdersCount > 0)
{
//
// Check Support Order Age ...
continue;
}
}
//
// at the moment we are sure the jPosition is Open Support Position ...
//
// First Sure there isn't any other Positions Open ...
// Ignore Support for Support Trades which their related Positions Exists Open ...
// TODO: Check and use this if required ...
int positionsCount = mTrader.CountPositions();
if (positionsCount > 1)
{
//
// Close Max In Profit Trade if it is long age ...
// Detect Positions ...
// TODO: here ...
// XPosition positions[];
// GetPositions();
// int ordersCount = CountPlacedSupports(symbol, period);
// double profit = mTrader.GetPositionsProfit(symbol);
// if (profit > 1 ||
// profit < -1 ||
// (profit < 0 &&
// ordersCount == 0))
// {
// continue;
// }
}
//
// then We Have to Check the Open Positions age ...
// ignore recently opesitions ...
int positionAge = GetPositionAge(
jPosition,
period);
bool isAgeTooOld = positionAge >= longAgeDetection;
if (!isAgeTooOld)
{
continue;
}
//
// Now Check Supported Before Or Not ...
int supportIndex = GetSupportsIndex(jPosition.ticket);
if (supportIndex < 0)
{
//
// This means we don't support it bere ...
//
XSupport jSupport;
//
jSupport.position = jPosition;
jSupport.lastSupportVolume = jPosition.volume;
jSupport.lastSupport = TimeToMilliSeconds(jPosition.openAt);
//
// Add Support ...
AddSupports(jSupport);
//
// Update Support Index ...
supportIndex = GetSupportsIndex(jPosition.ticket);
}
//
// Now we Have to Check Last Support Age ...
int supportAge = GetSupportAge(supportIndex);
isAgeTooOld = supportAge >= longAgeDetection;
if (!isAgeTooOld)
{
continue;
}
//
// Remove all Previously Executed Support Signals which not triggered ...
XOrder orders[];
GetOrders(
orders,
mSupports[supportIndex].position.symbol,
NULL, // All Type of Orders ...
NULL, // All State Of Orders ...
mSupports[supportIndex].position.period,
NULL // All Signallers type Orders ...
);
int ordersCount = ArraySize(orders);
if (ordersCount > 0)
{
//
for (int u = 0; u < ordersCount; u++)
{
//
XOrder uOrder = orders[u];
//
// Now we have to Make sure this Orders is Support Order ...
string uParams[];
bool isSupportOrder = ExtractSupportParams(
uOrder.comment,
uParams);
if (!isSupportOrder)
{
continue;
}
//
bool isCancelled = mTrader.CancelOrder(uOrder.ticket);
}
}
//
double lastSupportVolume = mSupports[supportIndex].lastSupportVolume * supportVolumeMultiplier;
//
// Here we Make Sure that we Have a Long Position which added in our Supports ...
// now we have to Eneable Equity Manager Support Signals for this Specific Signal ...
XSignal jSupportSignals[];
bool isSupportSignalsGenerated = GenerateSupportSignals(
mSupports[supportIndex].position,
jSupportSignals,
lastSupportVolume);
if (!isSupportSignalsGenerated)
{
continue;
}
//
// Execute Support Signals ...
bool isExecuted = ExecuteSupportSignals(
mSupports[supportIndex].position,
jSupportSignals);
if (isExecuted)
{
//
// Now we Have to Update Support Info to Prevent Multiple Supporting ...
//
datetime barTime = iTime(
mSupports[supportIndex].position.symbol,
mSupports[supportIndex].position.period,
0);
//
mSupports[supportIndex].lastSupportVolume = lastSupportVolume;
mSupports[supportIndex].lastSupport = TimeToMilliSeconds(barTime);
}
}
}
}
//
void HandleEquitySupportGuard()
{
//
double minVolumeFactor = 0.01;
double minProfitForEachTrade = 0.3;
//
int positionsCount = mTrader.CountPositions();
if (positionsCount < 2)
{
return;
}
//
// Retrieve Provider Count ...
int providersCount = ArraySize(mProviders);
if (providersCount <= 0)
{
return;
}
//
// Loop Through Registered Provider Instances ...
for (int i = 0; i < providersCount; i++)
{
//
X121SignalProvider iSProvider = mProviders[i];
//
string symbol = iSProvider.symbol;
ENUM_TIMEFRAMES period = iSProvider.period;
//
XPosition positions[];
GetPositions(
positions,
symbol,
NULL, // All Position Types ...
period);
positionsCount = ArraySize(positions);
if (positionsCount < 2)
{
continue;
}
//
double profit = 0;
double requiredProfit = 0;
//
for (int j = 0; j < positionsCount; j++)
{
//
XPosition jPosition = positions[j];
//
profit += jPosition.profit;
requiredProfit += ((jPosition.volume / minVolumeFactor) * minProfitForEachTrade) + (-1 * jPosition.swap);
}
//
bool isProfitPassed = profit >= requiredProfit;
if (!isProfitPassed)
{
continue;
}
//
string comment = "EQM Close ...";
int closed = mTrader.ClosePositions(
positions,
comment);
//
bool isClosed = closed == positionsCount;
if (isClosed)
{
//
Clean(mSupports);
//
string message = "Equity Management Close (" + ToString(positionsCount) + ") due Hedging by: " + ToString(profit);
//
LogMessage(message);
}
}
}
//
//
//
//
void HandleEquityManagement()
{
//
// TODO: add this to Configurations ...
int longAgeDetection = 35;
double supportVolumeMultiplier = 2;
//
// Check Equity ...
bool hasEquity = CheckEquityForTrade();
if (hasEquity)
{
return;
}
//
// Retrieve Provider Count ...
int providersCount = ArraySize(mProviders);
if (providersCount <= 0)
{
return;
}
//
// Loop Through Registered Provider Instances ...
for (int i = 0; i < providersCount; i++)
{
//
X121SignalProvider iSProvider = mProviders[i];
//
string symbol = iSProvider.symbol;
ENUM_TIMEFRAMES period = iSProvider.period;
XSCX121Provider *analyzer = iSProvider.provider;
//
// TODO: Complete this here ...
}
}
//
void HandleEquitySupportGuard()
{
//
double minVolumeFactor = 0.01;
double minProfitForEachTrade = 0.3;
//
int positionsCount = mTrader.CountPositions();
if (positionsCount < 2)
{
return;
}
//
// Retrieve Provider Count ...
int providersCount = ArraySize(mProviders);
if (providersCount <= 0)
{
return;
}
//
// Loop Through Registered Provider Instances ...
for (int i = 0; i < providersCount; i++)
{
//
X121SignalProvider iSProvider = mProviders[i];
//
string symbol = iSProvider.symbol;
ENUM_TIMEFRAMES period = iSProvider.period;
//
XPosition positions[];
GetPositions(
positions,
symbol,
NULL, // All Position Types ...
period);
positionsCount = ArraySize(positions);
if (positionsCount < 2)
{
continue;
}
//
double profit = 0;
double requiredProfit = 0;
//
for (int j = 0; j < positionsCount; j++)
{
//
XPosition jPosition = positions[j];
//
profit += jPosition.profit;
requiredProfit += ((jPosition.volume / minVolumeFactor) * minProfitForEachTrade) + (-1 * jPosition.swap);
}
//
bool isProfitPassed = profit >= requiredProfit;
if (!isProfitPassed)
{
continue;
}
//
string comment = "EQM Close ...";
int closed = mTrader.ClosePositions(
positions,
comment);
//
bool isClosed = closed == positionsCount;
if (isClosed)
{
//
Clean(mSupports);
//
string message = "Equity Management Close (" + ToString(positionsCount) + ") due Hedging by: " + ToString(profit);
//
LogMessage(message);
}
}
}
//
// Since we Have to Add Some Sorts of Support Signals for
// All Issued Signals ...
// here we Implement Support Signals to Attached all Signallers ...
// //
// // Peaks Break Out Signal ...
// XSignal pBreakoutSignal;
// //
// // Vales BreakOut Signal ...
// // XSignal vBreakoutSignal;
// //
// pBreakoutSignal.symbol = conditions.symbol;
// pBreakoutSignal.period = conditions.period;
// pBreakoutSignal.type = POSITION_TYPE_BUY;
// //
// // Since Price above Current Entry ...
// // we SEt Sell Stop ...
// pBreakoutSignal.mode = X_ORDER_MODE_STOP;
// //
// double entry = NormalizePrice(
// conditions.xpvInfo.peak,
// conditions.symbol);
// pBreakoutSignal.entry = entry;
// //
// double tpPoint = 30;
// double tpPrice = PointToPrice(
// mConditions.symbol,
// tpPoint);
// double tp = entry + tpPrice;
// pBreakoutSignal.tp = tp;
// pBreakoutSignal.sl = 0;
// //
// pBreakoutSignal.volume = 0.02;
// //
// Copy(
// conditions.signal.providers,
// pBreakoutSignal.providers);
// //
// Add(
// pBreakoutSignal,
// conditions.signal.supports);
//
// Since we Have to Add Some Sorts of Support Signals for
// All Issued Signals ...
// here we Implement Support Signals to Attached all Signallers ...
// //
// // Peaks Break Out Signal ...
// XSignal pBreakoutSignal;
// //
// // Vales BreakOut Signal ...
// XSignal vBreakoutSignal;
// //
// vBreakoutSignal.symbol = conditions.symbol;
// vBreakoutSignal.period = conditions.period;
// vBreakoutSignal.type = POSITION_TYPE_SELL;
// //
// // Since Price above Current Entry ...
// // we SEt Sell Stop ...
// vBreakoutSignal.mode = X_ORDER_MODE_LIMIT;
// //
// double entry = NormalizePrice(
// conditions.xpvInfo.peak,
// conditions.symbol);
// vBreakoutSignal.entry = entry;
// //
// double tpPoint = 30;
// double tpPrice = PointToPrice(
// mConditions.symbol,
// tpPoint);
// double tp = entry - tpPrice;
// vBreakoutSignal.tp = tp;
// vBreakoutSignal.sl = 0;
// //
// vBreakoutSignal.volume = 0.02;
// //
// Copy(
// conditions.signal.providers,
// vBreakoutSignal.providers);
// //
// Add(
// vBreakoutSignal,
// conditions.signal.supports);