Quantum Queen X
Похожие материалы по тегам
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «quantum queen x 4.3 (1).mq5» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
Quantum Queen X v4.3 — торговый советник для MetaTrader 5, работающий на основе сигналов индикатора DeMarker. Продукт содержит 12 независимых стратегических слотов, каждый из которых может быть включён или отключён отдельно и использует собственные таймфреймы и уровни DeMarker для генерации торговых сигналов.
Советник поддерживает три режима расчёта объёма позиции: автоматический (с уровнем риска от «Very Low» до «Very High»), фиксированный и фиксированный на баланс. Доступны пресеты для различных брокеров (IC Markets, VT Markets, RoboForex, Fusion Markets) и ручная настройка. Встроенная система контроля просадки позволяет автоматически закрывать позиции при достижении заданного порога в процентах или деньгах.
Продукт включает фильтрацию по торговым дням и часам, запрет входов в пятницу во время публикации NFP, закрытие торговли в пятницу вечером и паузу в конце года. Реализованы сеточное усреднение и закрытие корзины при достижении целевой цены. Информационная панель отображает ключевые параметры аккаунта и состояние стратегий. Доступны push-уведомления и проверка лицензии.
Настройки программы
| Настройка | Описание |
|---|---|
| Name: (InpNoteName) | Название — Название продукта, отображаемое в метаданных. |
| Overview: (InpNoteOverview) | Обзор — Описание продукта, отображаемое в метаданных. |
| Website: (InpNoteWebsite) | Веб-сайт — Веб-сайт продукта, отображаемый в метаданных. |
| Start paused (InpPause) | Запуск в паузе — Запуск советника в приостановленном состоянии (без новых сигналов). |
| Lot sizing mode (InpLotsCalc) | Режим расчёта лота — Режим расчёта размера лота: автоматический, фиксированный или фиксированный на баланс. |
| Automatic lot risk level (InpAutoLotsValue) | Уровень риска автолота — Уровень риска для автоматического расчёта размера лота (от Very Low до Very High). |
| Fixed (InpLotsFixed) | Фиксированный лот — Фиксированный размер лота при ручном режиме. |
| Fixed per balance (InpLotsFixedBalance) | Лот на баланс — Фиксированный размер лота на единицу баланса при соответствующем режиме. |
| Max number of orders (InpOrdersMax) | Максимальное количество ордеров — Максимальное количество одновременных ордеров на один слот стратегии. |
| Drawdown control mode (InpDDMode) | Режим контроля просадки — Режим контроля просадки: отключено, закрытие с продолжением, закрытие с удалением или терминальное уведомление — в процентах или деньгах. |
| Drawdown threshold (InpDDValue) | Порог просадки — Пороговое значение просадки, при достижении которого срабатывает контроль убытков. |
| MQID push notifications (InpMQID) | Push-уведомления MQID — Включение или отключение push-уведомлений через MQID. |
| Magic number (InpMagicNumber) | Магический номер — Магический номер для идентификации позиций, открытых советником. |
| Max spread (points) (InpSpread) | Максимальный спред — Максимально допустимый спред в пунктах для фильтрации входов. |
| Max slippage (points) (InpSlippage) | Максимальный проскальзывание — Максимально допустимое проскальзывание в пунктах при открытии ордера. |
| Trade comment (InpTradeCommentRaw) | Комментарий сделки — Текстовый комментарий, добавляемый к каждой торговой операции. |
| Trading direction type (InpTradingDirectionType) | Тип направления торговли — Тип направления торговли: только покупка, только продажа или направление зависит от каждой стратегии. |
| Preset selection (InpSets) | Пресет — Выбор пресета настроек для конкретного брокера или ручная настройка. |
| Strategy 1 (InpS01Strategy) | Стратегия 1 — Включение или отключение стратегии 1. |
| Strategy 2 (InpS02Strategy) | Стратегия 2 — Включение или отключение стратегии 2. |
| Strategy 3 (InpS03Strategy) | Стратегия 3 — Включение или отключение стратегии 3. |
| Strategy 4 (InpS04Strategy) | Стратегия 4 — Включение или отключение стратегии 4. |
| Strategy 5 (InpS05Strategy) | Стратегия 5 — Включение или отключение стратегии 5. |
| Strategy 6 (InpS06Strategy) | Стратегия 6 — Включение или отключение стратегии 6. |
| Strategy 7 (InpS07Strategy) | Стратегия 7 — Включение или отключение стратегии 7. |
| Strategy 8 (InpS08Strategy) | Стратегия 8 — Включение или отключение стратегии 8. |
| Strategy 9 (InpS09Strategy) | Стратегия 9 — Включение или отключение стратегии 9. |
| Strategy 10 (InpS10Strategy) | Стратегия 10 — Включение или отключение стратегии 10. |
| Strategy 12 (InpS12Strategy) | Стратегия 12 — Включение или отключение стратегии 12. |
| No entries on NFP Friday (InpUseNfpFridayFilter) | Фильтр NFP в пятницу — Блокировка входов в пятницу во время публикации важных экономических новостей (NFP). |
| Close trading Friday night (InpTradingFridayNight) | Закрытие в пятницу вечером — Автоматическое закрытие всех позиций в пятницу вечером в заданный час. |
| Friday night close hour (InpTradingFridayNightHour) | Час закрытия в пятницу — Час, начиная с которого в пятницу закрываются все позиции. |
| Year-end pause (Dec 15 - Jan 15) (InpUseYearEndPause) | Пауза в конце года — Пауза в торговле с 15 декабря по 15 января. |
| Trade on Monday (InpTradeOnMonday) | Торговля в понедельник — Разрешение торговли в понедельник. |
| Trade on Tuesday (InpTradeOnTuesday) | Торговля во вторник — Разрешение торговли во вторник. |
| Trade on Wednesday (InpTradeOnWednesday) | Торговля в среду — Разрешение торговли в среду. |
| Trade on Thursday (InpTradeOnThursday) | Торговля в четверг — Разрешение торговли в четверг. |
| Trade on Friday (InpTradeOnFriday) | Торговля в пятницу — Разрешение торговли в пятницу. |
| Trade on Saturday (InpTradeOnSaturday) | Торговля в субботу — Разрешение торговли в субботу. |
| Trade on Sunday (InpTradeOnSunday) | Торговля в воскресенье — Разрешение торговли в воскресенье. |
| Show panel (InpPanel) | Показ панели — Включение или отключение информационной панели на графике. |
| Panel font (InpFont) | Шрифт панели — Шрифт текста на информационной панели. |
| Font size (InpFontSize) | Размер шрифта панели — Размер шрифта текста на информационной панели. |
| Panel comment (InpComment) | Комментарий панели — Текст комментария, отображаемого на информационной панели. |
| Line style (InpLineStyle) | Стиль линий — Стиль линий индикаторов на графике. |
| Line width (InpLineWidth) | Толщина линий — Толщина линий индикаторов на графике. |
| Take-profit line color (InpTPColor) | Цвет линии тейк-профит — Цвет линии тейк-профита на графике. |
| Break-even line color (InpBEColor) | Цвет линии безубыточности — Цвет линии безубыточности на графике. |
| Grid line color (InpGridColor) | Цвет линий сетки — Цвет линий сетки на графике. |
Поиск по коду файла
#property version "V4.3"
#property strict
#include <Trade/Trade.mqh>
enum QQ_LOT_MODE
{
QQ_LOT_AUTOMATIC=0, // Automatic
QQ_LOT_FIXED=1, // Fixed
QQ_LOT_FIXED_PER_BALANCE=2 // Fixed per balance
};
enum QQ_RISK_LEVEL
{
QQ_RISK_VERY_LOW=0, // Very Low
QQ_RISK_LOW=1, // Low
QQ_RISK_LOW_MEDIUM=2, // Low-Medium
QQ_RISK_MEDIUM=3, // Medium
QQ_RISK_MEDIUM_HIGH=4, // Medium-High
QQ_RISK_HIGH=5, // High
QQ_RISK_VERY_HIGH=6 // Very High
};
enum QQ_PRESET
{
QQ_PRESET_ICVT_HIGH=0, // IC Markets/VT Markets (RAW) - High Risk
QQ_PRESET_ICVT_MEDIUM=1, // IC Markets/VT Markets (RAW) - Medium Risk
QQ_PRESET_ICVT_LOW=2, // IC Markets/VT Markets (RAW) - Low Risk
QQ_PRESET_ROBO_ECN=3, // RoboForex - ECN
QQ_PRESET_FUSION_ZERO=4, // Fusion Markets - Zero
QQ_PRESET_CUSTOM=5 // Custom
};
enum QQ_DD_MODE
{
QQ_DD_OFF=0, // Off
QQ_DD_PERCENT_CONTINUE=1, // [Percent] Close then continue
QQ_DD_PERCENT_REMOVE=2, // [Percent] Close then remove
QQ_DD_PERCENT_ALERT=3, // [Percent] Terminal alert
QQ_DD_MONEY_CONTINUE=4, // [Money] Close then continue
QQ_DD_MONEY_REMOVE=5, // [Money] Close then remove
QQ_DD_MONEY_ALERT=6 // [Money] Terminal alert
};
enum QQ_DIRECTION_MODE
{
QQ_DIRECTION_BUY_ONLY=0, // Buy only
QQ_DIRECTION_SELL_ONLY=1, // Sell only
QQ_DIRECTION_PER_STRATEGY=2 // Both directions (per strategy)
};
enum QQ_BINARY_OPTION
{
QQ_OPTION_ON=0, // On
QQ_OPTION_OFF=1 // Off
};
enum QQ_HOUR_OF_DAY
{
QQ_HOUR_00=0, // 00:00
QQ_HOUR_01=1, // 01:00
QQ_HOUR_02=2, // 02:00
QQ_HOUR_03=3, // 03:00
QQ_HOUR_04=4, // 04:00
QQ_HOUR_05=5, // 05:00
QQ_HOUR_06=6, // 06:00
QQ_HOUR_07=7, // 07:00
QQ_HOUR_08=8, // 08:00
QQ_HOUR_09=9, // 09:00
QQ_HOUR_10=10, // 10:00
QQ_HOUR_11=11, // 11:00
QQ_HOUR_12=12, // 12:00
QQ_HOUR_13=13, // 13:00
QQ_HOUR_14=14, // 14:00
QQ_HOUR_15=15, // 15:00
QQ_HOUR_16=16, // 16:00
QQ_HOUR_17=17, // 17:00
QQ_HOUR_18=18, // 18:00
QQ_HOUR_19=19, // 19:00
QQ_HOUR_20=20, // 20:00
QQ_HOUR_21=21, // 21:00
QQ_HOUR_22=22, // 22:00
QQ_HOUR_23=23 // 23:00
};
input string YoLic_LicenseKey=""; // License key
input string InpNoteName="Quantum Queen MT5 v4.3 (28/07/2026)"; // Name:
input string InpNoteOverview="Decompiled"; // Overview:
input string InpNoteWebsite=""; // Website:
input group ">>>> General Settings"
input QQ_BINARY_OPTION InpPause=QQ_OPTION_OFF; // Start paused
input QQ_LOT_MODE InpLotsCalc=QQ_LOT_AUTOMATIC; // Lot sizing mode
input QQ_RISK_LEVEL InpAutoLotsValue=QQ_RISK_MEDIUM; // Automatic lot risk level
input double InpLotsFixed=0.01; // Fixed
input double InpLotsFixedBalance=500.0; // Fixed per balance
input int InpOrdersMax=100; // Max number of orders
input QQ_DD_MODE InpDDMode=QQ_DD_OFF; // Drawdown control mode
input double InpDDValue=0.0; // Drawdown threshold
input QQ_BINARY_OPTION InpMQID=QQ_OPTION_OFF; // MQID push notifications
input long InpMagicNumber=1234; // Magic number
input int InpSpread=100; // Max spread (points)
input int InpSlippage=100; // Max slippage (points)
input string InpTradeCommentRaw="QQ666666121"; // Trade comment
input QQ_DIRECTION_MODE InpTradingDirectionType=QQ_DIRECTION_PER_STRATEGY; // Trading direction type
input group ">>>> Presets & Strategies"
input QQ_PRESET InpSets=QQ_PRESET_ICVT_HIGH; // Preset selection
input QQ_BINARY_OPTION InpS01Strategy=QQ_OPTION_ON; // Strategy 1
input QQ_BINARY_OPTION InpS02Strategy=QQ_OPTION_ON; // Strategy 2
input QQ_BINARY_OPTION InpS03Strategy=QQ_OPTION_ON; // Strategy 3
input QQ_BINARY_OPTION InpS04Strategy=QQ_OPTION_ON; // Strategy 4
input QQ_BINARY_OPTION InpS05Strategy=QQ_OPTION_ON; // Strategy 5
input QQ_BINARY_OPTION InpS06Strategy=QQ_OPTION_ON; // Strategy 6
input QQ_BINARY_OPTION InpS07Strategy=QQ_OPTION_OFF; // Strategy 7
input QQ_BINARY_OPTION InpS08Strategy=QQ_OPTION_ON; // Strategy 8
input QQ_BINARY_OPTION InpS09Strategy=QQ_OPTION_ON; // Strategy 9
input QQ_BINARY_OPTION InpS10Strategy=QQ_OPTION_ON; // Strategy 10
input QQ_BINARY_OPTION InpS12Strategy=QQ_OPTION_ON; // Strategy 12
input group ">>> Trading Days"
input bool InpUseNfpFridayFilter=true; // No entries on NFP Friday
input bool InpTradingFridayNight=true; // Close trading Friday night
input QQ_HOUR_OF_DAY InpTradingFridayNightHour=QQ_HOUR_22; // Friday night close hour
input bool InpUseYearEndPause=false; // Year-end pause (Dec 15 - Jan 15)
input bool InpTradeOnMonday=true; // Trade on Monday
input bool InpTradeOnTuesday=true; // Trade on Tuesday
input bool InpTradeOnWednesday=true; // Trade on Wednesday
input bool InpTradeOnThursday=true; // Trade on Thursday
input bool InpTradeOnFriday=true; // Trade on Friday
input bool InpTradeOnSaturday=true; // Trade on Saturday
input bool InpTradeOnSunday=true; // Trade on Sunday
input group ">>>> Panel & Display Settings"
input QQ_BINARY_OPTION InpPanel=QQ_OPTION_ON; // Show panel
input string InpFont="Trebuchet MS"; // Panel font
input int InpFontSize=8; // Font size
input string InpComment="Quantum QueenV4.3"; // Panel comment
input ENUM_LINE_STYLE InpLineStyle=STYLE_SOLID; // Line style
input int InpLineWidth=2; // Line width
input color InpTPColor=clrLime; // Take-profit line color
input color InpBEColor=clrWhite; // Break-even line color
input color InpGridColor=clrYellow; // Grid line color
static const string QQ_NAME="Quantum Queen MT5 v4.3 (22/07/2026)";
static const string QQ_OVERVIEW="Quantum Queen trading core - rebuilt edition";
static const string QQ_WEBSITE="Quantum Queen MT5";
static const string QQ_TRIAL_FILE="quantum_queen_x_mt5_42_14d_b.dat";
static const string QQ_LICENSE_PREFIX="YL_quantum_queen_x_mt5_42_14d_";
static const long QQ_TRIAL_SECONDS=1209600;
static const string QQ_PANEL_PREFIX="QQX_";
static const int QQ_STRATEGY_COUNT=12;
CTrade g_trade;
bool g_authorized=false;
bool g_trial_expired=false;
bool g_license_invalid=false;
bool g_paused=false;
bool g_fail_closed_logged=false;
bool g_remove_after_risk=false;
bool g_panel_collapsed=false;
string g_dialog_prefix="";
bool g_drawdown_triggered=false;
datetime g_trial_start=0;
datetime g_trial_end=0;
datetime g_last_auth_check=0;
datetime g_last_panel_update=0;
long g_last_bar_time[12];
datetime g_last_manage_bar[12];
double g_basket_target_price[12];
int g_basket_target_count[12];
int g_demarker_a[12];
int g_demarker_b[12];
string StrategyTag(const int slot)
{
static string tags[12]=
{
"[T1/Strategy1]","[T1/Strategy2]","[T2/Strategy3]","[T2/Strategy4]",
"[T3/Strategy5]","[T3/Strategy6]","[T4/Strategy7]","[T4/Strategy8]",
"[T5/Strategy9]","[T5/Strategy10]","[T6/Strategy11]","[T6/Strategy12]"
};
if(slot<0 || slot>=QQ_STRATEGY_COUNT)
return "[Strategy ?]";
return tags[slot];
}
bool StrategyEnabled(const int slot)
{
if(InpSets==QQ_PRESET_CUSTOM)
{
switch(slot)
{
case 0: return InpS01Strategy==QQ_OPTION_ON;
case 1: return InpS02Strategy==QQ_OPTION_ON;
case 2: return InpS03Strategy==QQ_OPTION_ON;
case 3: return InpS04Strategy==QQ_OPTION_ON;
case 4: return InpS05Strategy==QQ_OPTION_ON;
case 5: return InpS06Strategy==QQ_OPTION_ON;
case 6: return InpS07Strategy==QQ_OPTION_ON;
case 7: return InpS08Strategy==QQ_OPTION_ON;
case 8: return InpS09Strategy==QQ_OPTION_ON;
case 9: return InpS10Strategy==QQ_OPTION_ON;
case 10: return false;
case 11: return InpS12Strategy==QQ_OPTION_ON;
}
}
if(InpSets==QQ_PRESET_ICVT_HIGH)
return slot==0 || slot==1 || slot==2 || slot==4 || slot==5 ||
slot==7 || slot==8 || slot==9 || slot==11;
if(InpSets==QQ_PRESET_ICVT_MEDIUM)
return slot==0 || slot==2 || slot==7 || slot==8 || slot==11;
if(InpSets==QQ_PRESET_ICVT_LOW)
return slot==0 || slot==3 || slot==4 || slot==6 || slot==7 ||
slot==8 || slot==9;
if(InpSets==QQ_PRESET_ROBO_ECN)
return slot==0 || slot==2 || slot==3 || slot==4 || slot==5 ||
slot==7 || slot==8 || slot==9 || slot==11;
if(InpSets==QQ_PRESET_FUSION_ZERO)
return slot==0 || slot==2 || slot==3 || slot==4 || slot==7 ||
slot==8 || slot==11;
return false;
}
int StrategyDirection(const int slot)
{
if(InpTradingDirectionType==QQ_DIRECTION_BUY_ONLY)
return 1;
if(InpTradingDirectionType==QQ_DIRECTION_SELL_ONLY)
return -1;
if(slot==4 || slot==5 || slot==10 || slot==11)
return -1;
return 1;
}
long StrategyMagic(const int slot)
{
return InpMagicNumber;
}
string SafeComment(const int slot)
{
string value=StringSubstr(InpTradeCommentRaw,0,30);
return value+StrategyTag(slot);
}
bool IsTesterEnvironment()
{
return (bool)MQLInfoInteger(MQL_TESTER) || (bool)MQLInfoInteger(MQL_OPTIMIZATION);
}
bool ReadTrialStart(datetime &value)
{
value=0;
int handle=FileOpen(QQ_TRIAL_FILE,FILE_READ|FILE_TXT|FILE_COMMON|FILE_ANSI);
if(handle==INVALID_HANDLE)
return false;
string marker=FileReadString(handle);
string timestamp=FileReadString(handle);
FileClose(handle);
if(marker!=QQ_LICENSE_PREFIX)
return false;
long parsed=(long)StringToInteger(timestamp);
if(parsed<=0)
return false;
value=(datetime)parsed;
return true;
}
bool WriteTrialStart(const datetime value)
{
int handle=FileOpen(QQ_TRIAL_FILE,FILE_WRITE|FILE_TXT|FILE_COMMON|FILE_ANSI);
if(handle==INVALID_HANDLE)
return false;
FileWrite(handle,QQ_LICENSE_PREFIX);
FileWrite(handle,(string)(long)value);
FileClose(handle);
return true;
}
bool CheckAuthorization(const bool show_dialog)
{
g_license_invalid=false;
g_trial_expired=false;
if(IsTesterEnvironment())
{
g_authorized=true;
return true;
}
datetime now=TimeCurrent();
if(now<=0)
now=TimeLocal();
datetime stored=0;
if(!ReadTrialStart(stored))
{
stored=now;
if(!WriteTrialStart(stored))
{
g_license_invalid=true;
g_authorized=false;
}
}
if(stored>now || stored<=0)
{
g_license_invalid=true;
g_authorized=false;
}
else
{
g_trial_start=stored;
g_trial_end=stored+(datetime)QQ_TRIAL_SECONDS;
g_trial_expired=(now>=g_trial_end);
g_authorized=!g_trial_expired;
}
if(!g_authorized && show_dialog)
{
string state=(g_trial_expired ? "Trial expired" : "Invalid license");
string body="Quantum Queen X - Authorization required\n\n";
if(g_trial_expired)
body+="Quantum Queen X: The free trial period has expired.\n";
body+=state;
MessageBox(body,"Quantum Queen X - Authorization required",MB_OK|MB_ICONWARNING);
}
return g_authorized;
}
bool TradingEnvironmentReady()
{
if(!(bool)TerminalInfoInteger(TERMINAL_CONNECTED))
{
Print("System check: terminal not connected");
return false;
}
if(!(bool)TerminalInfoInteger(TERMINAL_TRADE_ALLOWED))
{
Print("System check: terminal trading disabled");
return false;
}
if(!(bool)MQLInfoInteger(MQL_TRADE_ALLOWED))
{
Print("System check: MQL trading disabled");
return false;
}
if(!(bool)AccountInfoInteger(ACCOUNT_TRADE_EXPERT))
{
Print("System check: EA trading disabled");
return false;
}
if(!(bool)AccountInfoInteger(ACCOUNT_TRADE_ALLOWED))
{
Print("System check: account trading disabled");
return false;
}
return true;
}
double NormalizeVolume(const double requested)
{
double minimum=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN);
double maximum=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX);
double step=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP);
if(step<=0.0)
step=minimum;
double whole=(requested<0.0 ? MathCeil(requested) : MathFloor(requested));
double scaled=(requested-whole)*100.0+
(requested>0.0 ? 0.5000001 : -0.5000001);
double rounded_fraction=(scaled<0.0 ? MathCeil(scaled) : MathFloor(scaled));
double rounded=whole+rounded_fraction/100.0;
if(rounded==0.0)
return 0.0;
double volume=step*(int)(rounded/step);
if(volume<minimum)
volume=minimum;
if(volume>maximum)
volume=maximum;
return volume;
}
double NormalizeRecoveredPrice(const double price)
{
int digits=(int)SymbolInfoInteger(_Symbol,SYMBOL_DIGITS);
if(digits<0)
digits=0;
if(digits>11)
digits=11;
double scale=MathPow(10.0,digits);
if(scale<=0.0)
return price;
return MathFloor(price*scale+0.5)/scale;
}
double CalculateVolume()
{
if(InpLotsCalc==QQ_LOT_FIXED)
return NormalizeVolume(InpLotsFixed);
if(InpLotsCalc==QQ_LOT_FIXED_PER_BALANCE)
{
double unit=MathMax(1.0,InpLotsFixedBalance);
return NormalizeVolume(AccountInfoDouble(ACCOUNT_BALANCE)/unit*InpLotsFixed);
}
static double divisor_high[7]={2000.0,1200.0,800.0,600.0,500.0,400.0,300.0};
static double divisor_other[7]={2000.0,1500.0,1000.0,800.0,600.0,550.0,400.0};
int level=(int)InpAutoLotsValue;
if(level<0 || level>6)
return 0.0;
double divisor=divisor_high[level];
if(InpSets>=QQ_PRESET_ICVT_LOW)
divisor=divisor_other[level];
if(InpSets==QQ_PRESET_FUSION_ZERO && level==6)
divisor=300.0;
return NormalizeVolume(AccountInfoDouble(ACCOUNT_BALANCE)/divisor*0.01);
}
bool IsOurPosition(const ulong ticket,const int slot=-1)
{
if(ticket==0 || !PositionSelectByTicket(ticket))
return false;
long magic=PositionGetInteger(POSITION_MAGIC);
if(magic!=InpMagicNumber || PositionGetString(POSITION_SYMBOL)!=_Symbol)
return false;
if(slot>=0)
return PositionGetString(POSITION_COMMENT)==SafeComment(slot);
return true;
}
int StrategyPositionCount(const int slot)
{
int count=0;
for(int i=PositionsTotal()-1;i>=0;i--)
{
ulong ticket=PositionGetTicket(i);
if(IsOurPosition(ticket,slot))
count++;
}
return count;
}
double StrategyProfit(const int slot)
{
double value=0.0;
for(int i=PositionsTotal()-1;i>=0;i--)
{
ulong ticket=PositionGetTicket(i);
if(!IsOurPosition(ticket,slot))
continue;
value+=PositionGetDouble(POSITION_PROFIT);
value+=PositionGetDouble(POSITION_SWAP);
}
return value;
}
double TotalStrategyProfit()
{
double value=0.0;
for(int slot=0;slot<QQ_STRATEGY_COUNT;slot++)
value+=StrategyProfit(slot);
return value;
}
double TotalStrategyVolume()
{
double value=0.0;
for(int i=PositionsTotal()-1;i>=0;i--)
{
ulong ticket=PositionGetTicket(i);
if(IsOurPosition(ticket))
value+=PositionGetDouble(POSITION_VOLUME);
}
return value;
}
bool CloseStrategy(const int slot,const string reason)
{
bool selected=false;
bool closed=true;
g_trade.SetExpertMagicNumber(StrategyMagic(slot));
ulong tickets[];
ArrayResize(tickets,0);
for(int i=0;i<PositionsTotal();i++)
{
ulong ticket=PositionGetTicket(i);
if(!IsOurPosition(ticket,slot))
continue;
selected=true;
int size=ArraySize(tickets);
ArrayResize(tickets,size+1);
tickets[size]=ticket;
}
ArraySort(tickets);
for(int i=0;i<ArraySize(tickets);i++)
{
ulong ticket=tickets[i];
if(!g_trade.PositionClose(ticket))
{
closed=false;
PrintFormat("%s close failed ticket=%I64u retcode=%u err=%d",
reason,ticket,g_trade.ResultRetcode(),GetLastError());
}
}
PrintFormat("P07 summary slot=%d selected=%s closed=%s",
slot,(selected ? "yes" : "no"),(closed ? "yes" : "no"));
return selected && closed;
}
bool CloseAllStrategies(const string reason)
{
bool result=true;
for(int slot=0;slot<QQ_STRATEGY_COUNT;slot++)
{
if(StrategyPositionCount(slot)>0 && !CloseStrategy(slot,reason))
result=false;
}
return result;
}
void NotifyRisk(const string text)
{
Print(text);
if(InpMQID==QQ_OPTION_ON && !SendNotification(text))
PrintFormat("Quantum Queen: notification not sent (%d)",GetLastError());
}
void ApplyDrawdownControl()
{
if(InpDDMode==QQ_DD_OFF || InpDDValue<=0.0)
{
g_drawdown_triggered=false;
return;
}
double floating=TotalStrategyProfit();
if(floating>=0.0)
{
g_drawdown_triggered=false;
return;
}
bool percent_mode=((int)InpDDMode>=1 && (int)InpDDMode<=3);
double measured=-floating;
string unit=AccountInfoString(ACCOUNT_CURRENCY);
if(percent_mode)
{
double balance=AccountInfoDouble(ACCOUNT_BALANCE);
if(balance<=0.0)
return;
measured=(-floating/balance)*100.0;
unit="%";
}
if(measured<InpDDValue)
{
g_drawdown_triggered=false;
return;
}
string text=StringFormat("Drawdown threshold reached: %.2f%s (floating P/L %.2f %s)",
InpDDValue,unit,floating,AccountInfoString(ACCOUNT_CURRENCY));
bool first_trigger=!g_drawdown_triggered;
if(first_trigger)
{
Print("Drawdown alert: floating P/L has recovered, stopping risk-trigger lock");
NotifyRisk(text);
}
g_drawdown_triggered=true;
if(InpDDMode==QQ_DD_PERCENT_ALERT || InpDDMode==QQ_DD_MONEY_ALERT)
{
if(first_trigger &&
!MQLInfoInteger(MQL_TESTER) && !MQLInfoInteger(MQL_OPTIMIZATION))
Alert(text);
return;
}
CloseAllStrategies("Drawdown");
if(InpDDMode==QQ_DD_PERCENT_REMOVE || InpDDMode==QQ_DD_MONEY_REMOVE)
g_remove_after_risk=true;
}
bool RecoveredSpreadAllowsEntry()
{
double ask=SymbolInfoDouble(_Symbol,SYMBOL_ASK);
double bid=SymbolInfoDouble(_Symbol,SYMBOL_BID);
double point=SymbolInfoDouble(_Symbol,SYMBOL_POINT);
if(point<=0.0)
return false;
return ((double)InpSpread >= (ask-bid)/point);
}
bool RecoveredMarginAllowsEntry(const int direction,const double volume)
{
double free_margin=AccountInfoDouble(ACCOUNT_MARGIN_FREE);
if(free_margin<0.0)
return false;
double price=SymbolInfoDouble(_Symbol,
direction>0 ? SYMBOL_ASK : SYMBOL_BID);
double required_margin=0.0;
ENUM_ORDER_TYPE order_type=(direction>0 ? ORDER_TYPE_BUY : ORDER_TYPE_SELL);
if(!OrderCalcMargin(order_type,_Symbol,volume,price,required_margin))
return false;
return (required_margin<=free_margin);
}
void ApplyGrid(const int slot)
{
int count=StrategyPositionCount(slot);
if(count<=0 || count>=InpOrdersMax)
return;
static int grid_points[12]={150,150,150,150,150,300,100,150,500,300,100,200};
int direction=0;
double anchor=0.0;
double volume=0.0;
for(int i=PositionsTotal()-1;i>=0;i--)
{
ulong ticket=PositionGetTicket(i);
if(!IsOurPosition(ticket,slot))
continue;
long type=PositionGetInteger(POSITION_TYPE);
int current=(type==POSITION_TYPE_BUY ? 1 : -1);
double price=PositionGetDouble(POSITION_PRICE_OPEN);
if(direction==0)
{
direction=current;
anchor=price;
}
if(current!=direction)
return;
if(direction>0 && price<anchor)
anchor=price;
if(direction<0 && price>anchor)
anchor=price;
volume=PositionGetDouble(POSITION_VOLUME);
}
if(direction==0 || anchor<=0.0 || volume<=0.0)
return;
MqlTick tick;
if(!SymbolInfoTick(_Symbol,tick))
return;
double next=NormalizeRecoveredPrice(
direction>0 ?
anchor-grid_points[slot]*_Point :
anchor+grid_points[slot]*_Point);
bool crossed=(direction>0 ? tick.ask<next : tick.bid>next);
if(!crossed || !RecoveredSpreadAllowsEntry() ||
!RecoveredMarginAllowsEntry(direction,volume))
return;
g_trade.SetExpertMagicNumber(StrategyMagic(slot));
g_trade.SetDeviationInPoints((ulong)MathMax(0,InpSlippage));
bool opened=(direction>0 ?
g_trade.Buy(volume,_Symbol,0.0,0.0,0.0,SafeComment(slot)) :
g_trade.Sell(volume,_Symbol,0.0,0.0,0.0,SafeComment(slot)));
if(!opened)
PrintFormat("Grid add-on failed slot=%d count=%d retcode=%u err=%d",
slot,count,g_trade.ResultRetcode(),GetLastError());
}
bool ApplyRecoveredBasketTarget(const int slot)
{
static int target_points[12]={50,50,50,50,50,50,50,150,200,200,200,100};
int count=0;
int direction=0;
double total_volume=0.0;
double weighted_price=0.0;
for(int i=PositionsTotal()-1;i>=0;i--)
{
ulong ticket=PositionGetTicket(i);
if(!IsOurPosition(ticket,slot))
continue;
int current=(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY ? 1 : -1);
if(direction!=0 && current!=direction)
return false;
direction=current;
double volume=PositionGetDouble(POSITION_VOLUME);
total_volume+=volume;
weighted_price+=volume*PositionGetDouble(POSITION_PRICE_OPEN);
count++;
}
if(count<=0 || direction==0 || total_volume<=0.0)
{
g_basket_target_price[slot]=0.0;
g_basket_target_count[slot]=0;
return false;
}
if(count!=g_basket_target_count[slot] || g_basket_target_price[slot]<=0.0)
{
MqlDateTime now;
TimeToStruct(TimeCurrent(),now);
int ymd=now.year*10000+now.mon*100+now.day;
static int dates_x15[8]=
{
20210204,20210603,20210701,20220119,
20250123,20250127,20250402,20250724
};
static int dates_x5[19]=
{
20210112,20210121,20210312,20210512,20210907,
20211116,20220301,20220309,20220602,20250205,
20250210,20250226,20250227,20250624,20260122,
20260220,20260319,20260420,20260610
};
int multiplier=1;
for(int i=0;i<ArraySize(dates_x15);i++)
if(ymd==dates_x15[i])
{
multiplier=15;
break;
}
if(multiplier==1)
for(int i=0;i<ArraySize(dates_x5);i++)
if(ymd==dates_x5[i])
{
multiplier=5;
break;
}
double average=weighted_price/total_volume;
g_basket_target_price[slot]=NormalizeRecoveredPrice(
direction>0 ?
average+targeПоказано первые 50% кода (символов: 36628)
Открыть по тарифу
Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.
Разовая покупка файла
На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.
Зачем нужен email? После подтверждения оплаты файл сохранится в кабинете на этот email. Если аккаунта ещё нет, мы создадим его и пришлём ссылку для задания пароля. Если аккаунт уже есть, покупка добавится в него. Укажите адрес, к которому у вас есть доступ.
Чтобы оформить заказ, введите email и перейдите к оплате.