Overdraft Profit System
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «!overdraft_profit_system3_v0.mq4» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
Overdraft Profit System — торговый советник для MetaTrader 4, работающий на основе сигналов пользовательского индикатора wlxFractals и нескольких режимов анализа рынка. Советник управляет виртуальными и реальными позициями, поддерживает реверс торговли, автоматический расчёт лота и наращивание позиции по заданным параметрам. Советник предоставляет несколько режимов открытия позиций: по сигналам индикатора фракталов, по ускорению цены, по волатильности и комбинированные режимы. Закрытие позиций настраивается через несколько режимов, включая фиксацию по тейк-профиту и стоп-лоссу, трейлинг по проценту прибыли и динамические стопы на основе волатильности.
Настройки программы
| Настройка | Описание |
|---|---|
| ? ??????? ?? ??????? ??????-?????????? (bMarketExec) | Рыночное исполнение — Включает исполнение ордеров по рыночной цене при открытии реальных позиций |
| ??????????????? ??? ???????? ?????????? (Slip) | Проскальзывание — Допустимое проскальзывание цены при исполнении ордеров в пунктах |
| true -????????? ???????? ?????? ?????????????? ???????? / false-? ??? ?? ??????????? (bRevers) | Реверс направления — true — инвертирует направление торговли; false — работает в направлении сигнала |
| ????? ????? ? ?????. (OpenMode) | Режим открытия — Выбор режима формирования сигнала на открытие позиции |
| ??? ??????. ???? =0, ?? ?????????? ?? (Lot) | Размер лота — Фиксированный размер лота; если равен 0, лот рассчитывается автоматически |
| ??????? ?? ??????? ??? ????. (MM) | Множитель лота — Множитель для расчёта лота при автоматическом размере |
| ??????????? ???????? ???? (Acceleration) | Ускорение — Порог ускорения цены для режима открытия по ускорению |
| ????? ????? ??? ??????? ????????????? (BarVolatile) | Бары волатильности — Количество баров для расчёта средней волатильности |
| ????????? ????????????? (kVolatile) | Коэффициент волатильности — Множитель волатильности для определения уровней открытия |
| ????????? ??? ?????????? ???? ????? ??????, ???? =0, ?? ???????? (LotKoef) | Коэффициент лота — Коэффициент увеличения лота при наращивании позиции; если 0 — отключено |
| ????? ????????? ???????, ????? ???????? ???????? ??????? ??? ?? LotKoef (LotKoefStart) | Начало наращивания — Номер ордера, начиная с которого применяется коэффициент LotKoef |
| ?????? ?????????? ????.??????? (VDeposit) | Виртуальный депозит — Сумма виртуального депозита для проверки маржи при расчёте лота |
| ????? ????????? ???? ??? ??????? ???????? ???? ?????????. (nDay) | Дни анализа — Количество дней для анализа истории при расчёте размера стопа |
| ????? ??????????? ?????? 0/1/2/3 (SpreadMode) | Режим спреда — Режим учёта спреда при фильтрации открытия ордеров |
| ?????? ????????????? ??????????? ?????? ??? SpreadMode=3 (FixSpread) | Фиксированный спред — Фиксированное значение спреда для режима SpreadMode=3 |
| ?????????? ????????? ???????? ?????? ??? ?????????? ???????? ?????? (AvgSpreadCount) | Количество для среднего спреда — Количество баров для расчёта среднего значения спреда |
| ????????? ??? ?????? ??????????? (AvgSpreadKoef) | Коэффициент среднего спреда — Множитель для сравнения текущего спреда со средним |
| ????? ???????? (CloseMode) | Режим закрытия — Режим определения условий закрытия позиции |
| ?????? ??????????? ??? CloseMode=2. ???? =0, ?? ?? ?????? (TP) | Тейк-профит — Тейк-профит в пунктах при CloseMode=2; если 0 — не задан |
| ?????? ???????? ??? CloseMode=2. ???? =0, ?? ?? ?????? (SL) | Стоп-лосс — Стоп-лосс в пунктах при CloseMode=2; если 0 — не задан |
| ??????????? ??? ?????????? ?????? ?? ????????????? (StopVolatile) | Стоп волатильности — Множитель волатильности для расчёта стоп-лосса и тейк-профита |
| ?????????? ???? ?? SL (bTralSL) | Трейлинг стоп-лосса — Включает трейлинг стоп-лосса для реальных позиций |
| =true - ????????? ????? ??????????? ????.?????? ?? ProcentProfit/CloseProcentProfit (bVTralTP) | Трейлинг TP виртуальных позиций — Включает трейлинг тейк-профита виртуальных позиций по проценту прибыли |
| ??????? ??????? ??????????? ??? ????? ???????? ? ???????, ???? =0, ?? ???? ????????. (ProcentProfit) | Процент прибыли — Процент прибыли от размера позиции для срабатывания трейлинга |
| ??????? ??? ??????? ???????? ??? ?????, ???? =0, ?? ???? ????????. (CloseProcentProfit) | Процент фиксации — Процент от трейлинговой прибыли для частичной фиксации |
| IndName | Имя индикатора — Имя пользовательского индикатора для формирования сигналов открытия |
| ???????????? ????? ?????? ?????? ????? ? ?????? ??? ???????????? ???????? (Equals) | Параметр совпадения — Параметр индикатора wlxFractals для определения уровня совпадения |
| ??????????? ????? ????? ????? ??? ???????? ????? (nLeftUp) | Бары слева вверх — Количество баров слева для определения уровня вверх по индикатору |
| ??????????? ????? ????? ?????? ??? ???????? ????? (nRightUp) | Бары справа вверх — Количество баров справа для определения уровня вверх по индикатору |
| ??????????? ????? ????? ????? ??? ???????? ???? (nLeftDown) | Бары слева вниз — Количество баров слева для определения уровня вниз по индикатору |
| // ??????????? ????? ????? ?????? ??? ???????? ???? (nRightDown) | Бары справа вниз — Количество баров справа для определения уровня вниз по индикатору |
| ?????????? ?? ????? ???? ?????? ????.???????. (bVirtInfo) | Виртуальная информация — Отображение информации о виртуальных позициях в окне комментариев |
| ?????????? ?? ????? ???? ?????? ????.???????. (bRealInfo) | Реальная информация — Отображение информации о реальных позициях в окне комментариев |
| ?????????? ?? ????? ???? ?????? ??? ????? (bSpreadInfo) | Информация о спреде — Отображение данных о текущем и среднем спреде в окне комментариев |
| ?????????? ???? ? ??????? ?? ????? (bShowComment) | Показать комментарии — Включает вывод текстовых сообщений в окно эксперта |
| ?????????? ??????????? ?????? ?? ????? (bShowVOrder) | Показать виртуальные ордера — Отображение виртуальных ордеров и сделок на графике в виде графических объектов |
Поиск по коду файла
#property strict
#include <stdlib.mqh>
#define OP_BALANCE 6
#define OP_MARKET 8
#define OP_ALL -1
int Magic=1234;/*Magic*/ // ????? ??????? ??????? ??
input bool bMarketExec=true;/*bMarketExec*/ // ? ??????? ?? ??????? ??????-??????????
input int Slip=0;/*Slip*/ // ??????????????? ??? ???????? ??????????
input string inf1="// ??????";
input bool bRevers=true;/*bRevers*/ // true -????????? ???????? ?????? ?????????????? ???????? / false-? ??? ?? ???????????
input int OpenMode=1;/*OpenMode*/ // ????? ????? ? ?????.
input double Lot=0.1;/*Lot*/ // ??? ??????. ???? =0, ?? ?????????? ??
input double MM=2;/*MM*/ //??????? ?? ??????? ??? ????.
input double Acceleration=1.5;/*Acceleration*/ // ??????????? ???????? ????
input int BarVolatile=24;/*BarVolatile*/ // ????? ????? ??? ??????? ?????????????
input double kVolatile=0.0;/*kVolatile*/ //????????? ?????????????
input double LotKoef=2;/*LotKoef*/ // ????????? ??? ?????????? ???? ????? ??????, ???? =0, ?? ????????
input int LotKoefStart=0;/*LotKoefStart*/ // ????? ????????? ???????, ????? ???????? ???????? ??????? ??? ?? LotKoef
input double VDeposit=5000;/*VDeposit*/ // ?????? ?????????? ????.???????
input int nDay=14;/*nDay*/ // ????? ????????? ???? ??? ??????? ???????? ???? ?????????.
input int SpreadMode=0;/*SpreadMode*/ // ????? ??????????? ?????? 0/1/2/3
input int FixSpread=5;/*FixSpread*/ // ?????? ????????????? ??????????? ?????? ??? SpreadMode=3
input int AvgSpreadCount=20;/*AvgSpreadCount*/ // ?????????? ????????? ???????? ?????? ??? ?????????? ???????? ??????
input double AvgSpreadKoef=2;/*AvgSpreadKoef*/ // ????????? ??? ?????? ???????????
input int CloseMode=2;/*CloseMode*/ // ????? ????????
input int TP=60;/*TP*/ // ?????? ??????????? ??? CloseMode=2. ???? =0, ?? ?? ??????
input int SL=60;/*SL*/ // ?????? ???????? ??? CloseMode=2. ???? =0, ?? ?? ??????
input double StopVolatile=2;/*StopVolatile*/ // ??????????? ??? ?????????? ?????? ?? ?????????????
input bool bTralSL=true;/*bTralSL*/ // ?????????? ???? ?? SL
input bool bVTralTP=true;/*bVTralTP*/ // =true - ????????? ????? ??????????? ????.?????? ?? ProcentProfit/CloseProcentProfit
input double ProcentProfit=80;/*ProcentProfit*/ // ??????? ??????? ??????????? ??? ????? ???????? ? ???????, ???? =0, ?? ???? ????????.
input double CloseProcentProfit=30;/*CloseProcentProfit*/ // ??????? ??? ??????? ???????? ??? ?????, ???? =0, ?? ???? ????????.
input string inf2="// ?????????";
input string IndName="wlxFractals";
input int Equals = 20;/*Equals*/ // ???????????? ????? ?????? ?????? ????? ? ?????? ??? ???????????? ????????
input int nLeftUp = 20;/*nLeftUp*/ // ??????????? ????? ????? ????? ??? ???????? ?????
input int nRightUp = 20;/*nRightUp*/ // ??????????? ????? ????? ?????? ??? ???????? ?????
input int nLeftDown = 20;/*nLeftDown*/ // ??????????? ????? ????? ????? ??? ???????? ????
input int nRightDown = 20;/*nRightDown*/ // // ??????????? ????? ????? ?????? ??? ???????? ????
input string inf3="// ????";
input bool bVirtInfo=true;/*bVirtInfo*/ // ?????????? ?? ????? ???? ?????? ????.???????.
input bool bRealInfo=true;/*bRealInfo*/ // ?????????? ?? ????? ???? ?????? ????.???????.
input bool bSpreadInfo=true;/*bSpreadInfo*/ // ?????????? ?? ????? ???? ?????? ??? ?????
input bool bShowComment=true;/*bShowComment*/ // ?????????? ???? ? ??????? ?? ?????
input bool bShowVOrder=true;/*bShowVOrder*/ // ?????????? ??????????? ?????? ?? ?????
string sID; // ID EA ??? ?????????? ??????????
bool bTesting; // ???? ??? ??????? ??????
double FreezLvl, StopLvl, Spread, Pnt, _Pnt, _Bid, _Ask, LotStep, LotSize, MaxLot, MinLot, TickSize, TickVal, ProfitCalcMode; int _Digit;
string g_inf;
double spread[]; int is=0;
double pBid=0; datetime fdtBid=0; int nBid=0; // ??? Acceleration
double pHi=0, pLo=0; // ??? Volatile
int OnInit()
{
// код доступен только после оплаты
}
void OnDeinit(const int reason)
{
if (IsTesting() || IsOptimization()) GlobalVariablesDeleteAll(sID);
ObjectsDeleteAll2(0, -1, sID); // ??????? ???????
}
void OnTick()
{
// код доступен только после оплаты
}
void main(int SysID, string smb, int tf)
{
RefreshParam(smb);
OpenVPos(SysID, smb, tf); // ?. ???????? ???????????? ??????
CloseVPos(SysID, smb, tf); // ?. ???????? ???????????? ??????
TralVPos(SysID, smb); // ?. ???? ??????????? ????.??????
OpenRPos(SysID, smb, tf); // ?. ???????? ????????? ??????
CloseRPos(SysID, smb, tf); // ?. ???????? ????????? ??????
TralRPos(SysID, smb); // ?. ??????????? ???????? ????????? ??????
int y=20;
VirtInfo(SysID, smb, tf, y);
RealInfo(SysID, smb, y);
SpreadInfo(SysID, smb, y);
}
int CheckOpenSignal(string smb, int tf, int &i)
{
INF("+????????? ?????? ???????? ???????????? ??????", true);
int n=iBars(smb, tf);
for (i=0; i<n; i++)
{
double f=iCustom(smb, tf, IndName, Equals, nLeftUp, nRightUp, nLeftDown, nRightDown, 0, i); if (f>0 && f!=EMPTY_VALUE) return(OP_BUY); // Buy: ???? ????????? ??????? wlxFractals ?????
f=iCustom(smb, tf, IndName, Equals, nLeftUp, nRightUp, nLeftDown, nRightDown, 1, i); if (f>0 && f!=EMPTY_VALUE) return(OP_SELL); // Sell: ???? ????????? ??????? wlxFractals ???????
}
return(-1);
}
double CountStopSize(int dir, string smb, int tf)
{
datetime dt=iTime(smb, PERIOD_H1, nDay*24-1); // ????? ????????? ??????
INF("+?????? ???????? ???? ???? ?? "+ITS(nDay)+" ???? (?? "+TTS(dt)+")", true);
int i=0;
double avg=0; int n=0;
while (iTime(smb, tf, i)>dt) // ???? ? ????????? nDay
{
double f1=GetNextFrac(ADIR(dir), smb, tf, i); if (f1<=0) break; i++;
double f2=GetNextFrac(dir, smb, tf, i); if (f2<=0) break; i++;
if (iTime(smb, tf, i)<dt) break;
avg+=fabs(f1-f2); n++;
}
INF("????? ??????????="+ITS(n)+" avg="+DTS(avg));
if (n<=0) return(0); // ???? ?? ????? ?? ?????? ??????????, ?? ??????
return(avg/n); // ????? ??????? ???????
}
double GetNextFrac(int dir, string smb, int tf, int &b)
{
int n=iBars(smb, tf);
for (int i=b; i<n; i++) { double f=iCustom(smb, tf, IndName, Equals, nLeftUp, nRightUp, nLeftDown, nRightDown, dir, i); if (f>0 && f!=EMPTY_VALUE) { b=i; return(f); } }
return(-1);
}
void OpenVPos(int SysID, string smb, int tf)
{
INF("");
INF("+?. ???????? ???????????? ??????", true);
if (SpreadMode==2 && is<AvgSpreadCount-1) { INF("???? ?????????? "+ITS(AvgSpreadCount)+" ????? ??? ??????"); return; }
if (CountOrders(-1, SysID, smb)!=0) { INF("???????? ?????? ??? ???????. ???? ????????"); return; }
int nmode=-1, ib=-1;
int dir=GetOpenModeDir(smb, tf, OpenMode, nmode, ib); if (dir<0) { INF("??????????? ???????? ????.?????? ?? ??????????"); return; }
string name[]; int n=SelectGV(sID+"VOrder.", name);
bool b=false; string sid=""; int id=0;
for (int i=0; i<n; i++)
{
int vdir=(int)GetGV(name[i]); if (vdir!=OP_BUY && vdir!=OP_SELL) continue;
sid=StringSubstr(name[i], StringLen(sID+"VOrder."));
id=STI(sid); sid=sID+"VO."+sid;
if (CheckGV(sid+".cl")) continue;
if (bShowVOrder) { DrawOrder(sid, id, (int)GetGV(name[i]), GetGV(sid+".op"), 0, 0); DrawDeal(sid, id, (int)GetGV(name[i]), Lot, GetGV(sid+".op"), (datetime)GetGV(sid+".dop"), 0, 0, 0, 0); }
b=true; break;
} //
if (b) { INF("???? ???????? V ?????? #"+ITS(id)); return; }
Print("??????? "+ITS(n)+" ????.??????? ? ???????. ???????? ???.");
if (ib>0) Print("?? ???? "+TTS(iTime(smb, tf, ib))+" ??? ?? ?????????.");
double op=NPR(dir);
id=int(GetTickCount()+MathRand()); // "?????" ???????????? ??????
sid=sID+"VO."+ITS(id);
SetGV(sID+"VOrder."+ITS(id), dir); // ???
double nlot=Lot; if (Lot<=0) nlot=(AccountBalance()/1000.0)*MM/100.0; nlot=NL(nlot); // ?????????? ? ??????????? ???
double lot=NL(nlot);
if (LotKoef!=0) // ??????????? ?????????? ??????
{
double plot=GetGV(sID+"Lot"); int No=(int)GetGV(sID+"N");
double lpip=0; int lid=VLastOrder(lpip);
Print("?????????? ????? ????.??????="+DTS(lpip/(Pnt*_Pnt),0)+" ????????? ???="+DTS(plot,2)+" ????? ???????="+ITS(No));
if (lpip>=0) { SetGV(sID+"Lot", nlot); SetGV(sID+"N", 0); }
else { if (plot>0) lot=NL(plot*MathPow(LotKoef, fmax(No+1-LotKoefStart,0))); SetGV(sID+"N", No+1); }
double vbal=CountVBalance();
if (vbal-(AccountBalance()-AccountFreeMarginCheck(smb, dir, lot))<=0)
{
Print("????.??????="+DTS(vbal,2)+", ?????????? ??? ?? ????????? ? ????????? ?????? ?? VDeposit="+DTS(VDeposit,2));
int did=int(GetTickCount()+MathRand()); // "?????" ?????? ???????????? ??????????
SetGV(sID+"VOrder."+ITS(did), OP_BALANCE); SetGV(sID+"VO."+ITS(did)+".prof", VDeposit); // ????????? ??????
SetGV(sID+"Lot", nlot); SetGV(sID+"N", 0); lot=nlot;
}
}
MqlDateTime md; datetime dop=TimeCurrent(md); // ??????? ?????
SetGV(sid+".op", op); SetGV(sid+".dop", dop); SetGV(sid+".lot", lot); DelGV(sid+".cl"); // ????????? ????????? ??????
string txt="Open V "+smb+" "+OTS(dir)+"#"+ITS(id)+" | op="+DTS(op)+" OpenMode="+ITS(OpenMode);
INF(txt); Print("+"+txt);
SetGV(sID+"Time", iTime(smb, tf, ib)); Print("????????? ????? ???????? ??????? "+TTS(iTime(smb, tf, ib)));
SetGV(sID+"VLast", id); // ????????? ????? ? ????? ????????
SetGV(sID+"Mode", nmode);
pLo=0; pHi=0; // ???????? ?????????????
if (bShowVOrder) { DrawOrder(sid, id, dir, op, 0, 0); DrawDeal(sid, id, dir, Lot, op, dop, 0, 0, 0, 0); }
}
int GetOpenModeDir(string smb, int tf, int mode, int &nmode, int &ib)
{
INF("+OpenMode="+ITS(OpenMode));
if (mode==0)
{
int dir=CheckOpenSignal(smb, tf, ib); if (dir<0) { INF("-???? ??????? ????????..."); return(-1); }
if (CheckGV(sID+"Time")) if (GetGV(sID+"Time")>=iTime(smb, tf, ib)) { INF("?? ???? ??????? ??? ????????? ?????"); return(-1); }
return(dir);
}
MqlDateTime md; datetime dop=TimeCurrent(md); // ??????? ?????
if (mode==1)
{
double a=0; if (dop-fdtBid>0) a=(nBid*1.0)/(dop-fdtBid);
if (fabs(a)>=Acceleration) return(a>0?OP_BUY:OP_SELL);
else { INF("????????="+DTS(a)+" < "+DTS(Acceleration,2)+" | tick="+ITS(nBid)+" pBid="+DTS(pBid)+" Bid="+DTS(_Bid)+" sec="+ITS(dop-fdtBid)); return(-1); }
}
if (mode==2)
{
double v=CountVolatile(smb, tf)*kVolatile;
if (_Bid>pLo+v && pLo>0) return(OP_BUY);
if (_Bid<pHi-v && pHi>0) return(OP_SELL);
INF("?????????????*k "+DTS(v/(Pnt*_Pnt),0)+" ? ????????? pHi="+DTS(pHi)+" / pLo="+DTS(pLo)+" / Bid="+DTS(_Bid)); return(-1);
}
int pmode=CheckGV(sID+"Mode")?(int)GetGV(sID+"Mode"):0;
if (mode==3)
{
nmode=2;
if (pmode!=2) return(GetOpenModeDir(smb, tf, 1, nmode, ib)); else return(GetOpenModeDir(smb, tf, 2, nmode, ib));
}
if (mode==4)
{
nmode=2;
if (pmode!=2) { if (pmode!=1) { nmode=1; return(GetOpenModeDir(smb, tf, 0, nmode, ib)); } else { nmode=2; return(GetOpenModeDir(smb, tf, 1, nmode, ib)); } }
else return(GetOpenModeDir(smb, tf, 2, nmode, ib));
}
return(-1);
}
int VLastOrder(double &pip)
{
if (!CheckGV(sID+"VLast")) return(-1);
int id=(int)GetGV(sID+"VLast");
string sid=sID+"VO."+ITS(id);
int dir=(int)GetGV(sID+"VOrder."+ITS(id));
double op=GetGV(sid+".op"), cl=GetGV(sid+".cl");
if (cl>0) pip=(cl-op)*SD(dir);
return(id);
}
void CloseVPos(int SysID, string smb, int tf)
{
INF("");
INF("+?. ???????? ???????????? ??????", true);
string name[]; int n=SelectGV(sID+"VOrder.", name);
MqlDateTime md; datetime dcl=TimeCurrent(md); // ??????? ?????
int ticketO[]; int no=GetTickets(-1, SysID, smb, ticketO);
int ticketH[]; int nh=GetTicketsH(-1, SysID, smb, ticketH);
for (int i=0; i<n; i++)
{
int dir=(int)GetGV(name[i]); if (dir!=OP_BUY && dir!=OP_SELL) continue;
string sid=StringSubstr(name[i], StringLen(sID+"VOrder."));
int id=STI(sid); sid=sID+"VO."+sid;
if (CheckGV(sid+".cl")) continue; // ??? ??????
double apr=APR(dir);
double op=GetGV(sid+".op"); datetime dop=(datetime)GetGV(sid+".dop");
double sl=CheckGV(sid+".sl")?GetGV(sid+".sl"):0, tp=CheckGV(sid+".tp")?GetGV(sid+".tp"):0;
if (bShowVOrder) { DrawOrder(sid, id, dir, op, sl, tp); DrawDeal(sid, id, dir, Lot, op, dop, 0, 0, sl, tp); }
bool b=false;
if (sl>0 && (sl-apr)*SD(dir)>=0) b=true;
if (tp>0 && (apr-tp)*SD(dir)>=0) b=true;
if (!b) { if (tp>0) INF("?? ?? ???????? "+DTS((tp-apr)*SD(dir)/(Pnt*_Pnt),0)+" ?."); if (sl>0) INF("?? ?? ???????? "+DTS((apr-sl)*SD(dir)/(Pnt*_Pnt),0)+" ?."); } // ???? ????? ???? ????????? ?? ??? ??
if (!b)
{
if (FindComment(ticketO, no, ITS(id)+"|")>0) { INF("????? ??? #"+ITS(id)+" ??? ??????"); continue; }
if (FindComment(ticketH, nh, ITS(id)+"|")<=0) { INF("????? ??? #"+ITS(id)+" ??? ?? ??????/?? ??????"); continue; }
}
SetGV(sid+".cl", apr); SetGV(sid+".dcl", dcl); // ??????? ?????
string txt="Close V "+smb+" "+OTS(dir)+"#"+ITS(id)+" | cl="+DTS(apr);
INF(txt); Print("+"+txt);
if (bShowVOrder) { DrawDeal(sid, id, dir, Lot, op, dop, apr, dcl, sl, tp); ObjectsDeleteAll2(0, OBJ_HLINE, sid); }
}
}
void TralVPos(int SysID, string smb)
{
INF("");
INF("+?. ???? ??????????? ????. ?????? ", true);
if ((ProcentProfit<=0 || CloseProcentProfit<=0) || !bVTralTP) { INF("-?? ??????????. ProcentProfit ??? CloseProcentProfit ? bVTralSL ==0"); return; }
string name[]; int n=SelectGV(sID+"VOrder.", name);
for (int i=0; i<n; i++)
{
int dir=(int)GetGV(name[i]); if (dir!=OP_BUY && dir!=OP_SELL) continue;
string sid=StringSubstr(name[i], StringLen(sID+"VOrder."));
int id=STI(sid); sid=sID+"VO."+sid;
if (CheckGV(sid+".cl")) continue; // ??? ??????
double apr=APR(dir);
double cop=GetGV(sid+".op");
double csl=CheckGV(sid+".sl")?GetGV(sid+".sl"):0, ctp=CheckGV(sid+".tp")?GetGV(sid+".tp"):0;
double wsl=(cop-csl)*SD(dir)*ProcentProfit/100; if (wsl<=0) { INF("? ????.?????? #"+ITS(id)+" ?? ?????????? ???????"); continue; }
if ((cop-apr)*SD(dir)<wsl) INF("???? ?????????? "+DTS(wsl/(Pnt*_Pnt),0)+" ?. ??????. ???????? "+DTS((wsl-(cop-apr)*SD(dir))/(Pnt*_Pnt),0));
else
{
double tp=cop-wsl*(1-CloseProcentProfit/100)*SD(dir);
if ((ctp-tp)*SD(dir)>0 || ctp==NP(0))
{
string txt="Tral V "+smb+" "+OTS(dir)+" #"+ITS(id)+" ctp="+DTS(ctp)+"->"+DTS(tp)+" id="+ITS(SysID);
INF(txt); Print("+"+txt); SetGV(sid+".tp", tp);
}
}
}
}
void OpenRPos(int SysID, string smb, int tf)
{
INF("");
INF("+?. ???????? ????????? ??????", true);
string name[]; int n=SelectGV(sID+"VOrder.", name); if (n<=0) { INF("???? V ??????"); return; }
int ticketO[]; int no=GetTickets(-1, SysID, smb, ticketO);
int ticketH[]; int nh=GetTicketsH(-1, SysID, smb, ticketH);
for (int i=0; i<n; i++)
{
int vdir=(int)GetGV(name[i]); if (vdir!=OP_BUY && vdir!=OP_SELL) continue;
string sid=StringSubstr(name[i], StringLen(sID+"VOrder."));
int id=STI(sid);
double vop=GetGV(sID+"VO."+sid+".op"); // ???? ???????? ????????????
if (CheckGV(sID+"VO."+sid+".cl")) continue; // ??????????? ????? ??? ??????
if (!CheckGV(sID+"VO."+sid+".lot")) { double lot=Lot; if (Lot<=0) lot=AccountBalance()*MM/100.0; lot=NL(lot); SetGV(sID+"VO."+sid+".lot", lot); }
double lot=GetGV(sID+"VO."+sid+".lot"); lot=NL(lot);
int dir=vdir; if (bRevers) dir=ADIR(dir); // ??????????? ?????
if (FindComment(ticketO, no, sid+"|")>0) { INF("????? ??? #"+sid+" ??? ??????"); continue; }
if (FindComment(ticketH, nh, sid+"|")>0) { INF("????? ??? #"+sid+" ??? ??????"); continue; }
double op=NPR(dir), apr=APR(dir);
int comp=0;
if (bRevers)
{
comp=GetComp();
if (comp>0 && (vop-op)*SD(dir)<comp*Pnt*_Pnt) { INF("???????? ????? "+DTS((comp-(vop-op)*SD(dir)/(Pnt*_Pnt)),0)+" ?."); continue; }
}
lot=NL(lot); // ??????????? ???
comp=int(fabs(vop-op)/(Pnt*_Pnt));
double d=CountStopSize(dir, smb, tf); string txt=("??????????? ?????? ??/??="+DTS(d/(Pnt*_Pnt),0)+" ?.");
INF(txt); if (d<=0) { INF("-???????? ?????? ??/??"); continue; }
Print(txt); // ??? ?????? ?????
double v=CountVolatile(smb, tf);
double tp=0, sl=0;
double dtp0=0, dsl0=0; if (CloseMode==0) { dtp0=d; dsl0=d; }
double dtp1=0, dsl1=0; if (CloseMode==1 || CloseMode==3 || CloseMode==4) { dtp1=TP*Pnt*_Pnt; dsl1=SL*Pnt*_Pnt; }
double dtp2=0, dsl2=0; if (CloseMode==2 || CloseMode==4) { dtp2=v*StopVolatile; dsl2=v*StopVolatile; }
if (CloseMode==0) { tp=dtp0; sl=dsl0; }
if (CloseMode==1) { tp=dtp1; sl=dsl1; }
if (CloseMode==2) { tp=dtp2; sl=dsl2; }
if (CloseMode==3) { if (dtp0>0) { if (dtp1>0) tp=fmin(dtp0, dtp1); else tp=dtp0; } else tp=dtp1; }
if (CloseMode==4)
{
if (dtp0>0) { if (dtp1>0) tp=fmin(dtp0, dtp1); else tp=dtp0; } else tp=dtp1;
if (dtp2>0) { if (tp>0) tp=fmin(dtp2, tp); else tp=dtp2; }
}
tp=NTP(dir, op, apr, tp/(Pnt*_Pnt), StopLvl);
sl=NSL(dir, op, apr, sl/(Pnt*_Pnt), StopLvl);
int ticket=-1;
if (bMarketExec) ticket=OrderSend(smb, dir, lot, op, Slip, 0, 0, sid+"|"+ITS(comp), SysID, 0, OTC(dir));
else ticket=OrderSend(smb, dir, lot, op, Slip, sl, tp, sid+"|"+ITS(comp), SysID, 0, OTC(dir));
txt="Open R "+smb+" "+OTS(dir)+"#"+ITS(ticket)+" op="+DTS(op)+" lot="+DTS(lot, 2)+" ? ????. id="+sid+" ?????????.="+ITS(comp)+" | magic="+ITS(SysID)+" | CloseMode="+ITS(CloseMode);
INF(txt);
if (ticket<=0) ErrorHandle(GetLastError(), -1, SysID, txt);
else
{
Print("+"+txt);
if (bMarketExec) PlaceStop(ticket, dir, SysID, smb, op, sl, tp);
if (vdir==OP_BUY)
{
if (sl>0 && sl<=vop) SetGV(sID+"VO."+sid+".sl", sl); else if (tp>0 && tp<=vop) SetGV(sID+"VO."+sid+".sl", tp);
if (tp>0 && tp>=vop) SetGV(sID+"VO."+sid+".tp", tp); else if (sl>0 && sl>=vop) SetGV(sID+"VO."+sid+".tp", sl);
}
else if (vdir==OP_SELL)
{
if (sl>0 && sl>=vop) SetGV(sID+"VO."+sid+".sl", sl); else if (tp>0 && tp>=vop) SetGV(sID+"VO."+sid+".sl", tp);
if (tp>0 && tp<=vop) SetGV(sID+"VO."+sid+".tp", tp); else if (sl>0 && sl<=vop) SetGV(sID+"VO."+sid+".tp", sl);
}
}
}
}
void CloseRPos(int SysID, string smb, int tf)
{
INF("");
INF("+?. ???????? ????????? ??????", true);
int ticket[], n=GetTickets(-1, SysID, smb, ticket); if (n<=0) { INF("wait orders"); return; }
for (int i=0; i<n; i++)
{
if (!OrderSelect(ticket[i], SELECT_BY_TICKET)) { INF("?????? ????????? ?????? "+ITS(ticket[i])); continue; }
int dir=OrderType(); double prof=OrderProfit(); double apr=APR(dir);
int c=StringFind(OrderComment(), "|"); if (c<0) { INF("?????? ??????????? "+OrderComment()); continue; }// ????? ?????? ?????????? ??? ????? ??? ??????
string sid=StringSubstr(OrderComment(), 0, c);
if (!CheckGV(sID+"VO."+sid+".cl")) { INF("#"+sid+" ??? ?????? (??? #"+ITS(ticket[i])+")"); continue; } // ????? ??? ?? ??????
string txt="Close R "+smb+" "+OTS(dir)+" #"+ITS(ticket[i])+"cl="+DTS(apr)+" prof="+DTS(OrderProfit(),2)+" pip="+DTS((OrderClosePrice()-OrderOpenPrice())/(Pnt*_Pnt),0);
INF(txt);
if (!OrderClose(ticket[i], OrderLots(), apr, Slip, OTC(dir))) ErrorHandle(GetLastError(), ticket[i], SysID, txt); else Print(txt);
}
}
void TralRPos(int SysID, string smb)
{
INF("");
INF("+?. ??????????? ???????? ????????? ??????", true);
if ((ProcentProfit<=0 || CloseProcentProfit<=0) && (SL<=0 || !bTralSL)) { INF("-?? ??????????. ProcentProfit ??? CloseProcentProfit ? SL ==0"); return; }
int ticket[], n=GetTickets(-1, SysID, smb, ticket); if (n<=0) { INF("wait orders"); return; }
for (int i=0; i<n; i++)
{
if (!OrderSelect(ticket[i], SELECT_BY_TICKET)) { INF("?????? ????????? ?????? "+ITS(ticket[i])); continue; }
int dir=OrderType(); RefreshParam(smb); double apr=APR(dir); // ???????? ?????????
double csl=ND(OrderStopLoss()); double cop=ND(OrderOpenPrice()); double ctp=ND(OrderTakeProfit());
if (MathAbs(ctp-apr)<=FreezLvl || MathAbs(csl-apr)<=FreezLvl) { INF(OTS(dir)+"#"+ITS(ticket[i])+" freezed"); continue; }
if (ProcentProfit>0 && CloseProcentProfit>0)
{
double wtp=(ctp-cop)*SD(dir)*ProcentProfit/100;
if (wtp<=0) { INF("? ?????? #"+ITS(ticket[i])+" ?? ?????????? ??????????"); }
else
{
if ((apr-cop)*SD(dir)<wtp) INF("???? ?????????? "+DTS(wtp/(Pnt*_Pnt),0)+" ?. ???????. ???????? "+DTS((wtp-(apr-cop)*SD(dir))/(Pnt*_Pnt),0));
else
{
double sl=NSL(dir, apr, apr, cop+wtp*(1-CloseProcentProfit/100)*SD(dir), StopLvl, false);
if ((sl-cop)*SD(dir)>0 && ((sl-csl)*SD(dir)>0 || csl==NP(0)))
{
string txt="Tral R "+smb+" "+OTS(dir)+" #"+ITS(ticket[i])+" csl="+DTS(csl)+"->"+DTS(sl)+" id="+ITS(SysID);
INF(txt);
if (!OrderModify(ticket[i], cop, sl, ctp, 0, OTC(dir))) ErrorHandle(GetLastError(), ticket[i], SysID, txt); else { Print("+"+txt); csl=sl; }
}
}
}
}
if (bTralSL && SL>0)
{
double sl=NSL(dir, apr, apr, SL, StopLvl);
if ((sl-csl)*SD(dir)>0 || csl==NP(0))
{
string txt="TralSL R (?? SL ? bTralSL) "+smb+" "+OTS(dir)+" #"+ITS(ticket[i])+" csl="+DTS(csl)+"->"+DTS(sl)+" id="+ITS(SysID);
INF(txt);
if (!OrderModify(ticket[i], cop, sl, ctp, 0, OTC(dir))) ErrorHandle(GetLastError(), ticket[i], SysID, txt); else Print("+"+txt);
}
}
}
}
void PlaceStop(int ticket, int dir, int SysID, string smb, double op, double nsl, double ntp)
{
RefreshParam(smb); double apr=APR(dir);
double sl=NSL(dir, op, apr, nsl, StopLvl, false);
double tp=NTP(dir, op, apr, ntp, StopLvl, false);
string txt="Place stops to "+OTS(dir)+"#"+ITS(ticket)+" op="+DTS(op)+" apr="+DTS(apr)+"| sl="+DTS(sl)+" tp="+DTS(tp)+" id="+ITS(SysID);
Print(txt); INF(txt);
int i=0;
while (i<5 && (tp>0 || sl>0))
{
RefreshParam(smb); apr=APR(dir);
sl=NSL(dir, op, apr, nsl, StopLvl, false);
tp=NTP(dir, op, apr, ntp, StopLvl, false);
txt="Place stops to "+OTS(dir)+"#"+ITS(ticket)+" op="+DTS(op)+" apr="+DTS(apr)+"| sl="+DTS(sl)+" tp="+DTS(tp)+" id="+ITS(SysID);
if (OrderModify(ticket, op, sl, tp, 0, OTC(dir))) break;
INF(txt); ErrorHandle(GetLastError(), -1, SysID, txt); Sleep(100); i++;
}
}
void VirtInfo(int SysID, string smb, int tf, int &y)
{
if (!bVirtInfo) return;
string txt[100]; int t=-1; color clr[100]; ArrayInitialize(clr, clrLightGray);
string name[]; int n=SelectGV(sID+"VOrder.", name);
int cdir=-1, cticket=0; double cop=0, cprof=0, cpprof=0, apr=0;
double prof=0, loss=0, depo=0, pprof=0, ploss=0; int nb=0, ns=0;
t++; txt[t]="======== VIRTUAL ======="; clr[t]=clrGray;
for (int i=0; i<n; i++)
{
string sid=StringSubstr(name[i], StringLen(sID+"VOrder."));
int id=STI(sid);
int dir=(int)GetGV(name[i]); // ??? ????????????
if (dir==OP_BALANCE) { depo+=GetGV(sID+"VO."+sid+".prof"); continue; } // ???? ?????????? ?????
double op=GetGV(sID+"VO."+sid+".op"); // ???? ???????? ????????????
double lot=GetGV(sID+"VO."+sid+".lot");
if (!CheckGV(sID+"VO."+sid+".cl"))
{
cdir=dir; cticket=id; cop=op; apr=APR(dir);
cpprof=(apr-cop)*SD(cdir); cprof=CalcProf(cdir, op, apr, lot);
t++; txt[t]=OTS(cdir)+"#"+ITS(cticket)+" | "+DTS(cop)+" | "+DTS(apr)+" | "+DTS(cpprof/(Pnt*_Pnt),0)+"?. | "+DTS(cprof,2)+"$"; clr[t]=OTC(cdir);
}
else
{
double cl=GetGV(sID+"VO."+sid+".cl");
double pip=(cl-op)*SD(dir);
if (pip>=0) { prof+=CalcProf(dir, op, cl, lot); pprof+=pip; } else { loss+=CalcProf(dir, op, cl, lot); ploss+=pip; }
if (dir==OP_BUY) nb++; else ns++;
}
}
if (cdir<0) { t++; txt[t]="???????? ???????: ???"; }
t++; txt[t]="?????????";
t++; txt[t]="????.??????: "+DTS(prof+loss+depo,2);
t++; txt[t]="???????? ???????: Sell "+ITS(ns)+" | Buy "+ITS(nb);
t++; txt[t]="???????: "+DTS(pprof/(Pnt*_Pnt),0)+" ?./"+DTS(prof,2);
t++; txt[t]="??????: "+DTS(ploss/(Pnt*_Pnt),0)+" ?./"+DTS(loss,2);
t++; txt[t]="?????: "+DTS((pprof+ploss)/(Pnt*_Pnt),0)+" ?./"+DTS(prof+loss,2);
t++; txt[t]="?????????";
t++; txt[t]="?????????????: "+DTS(CountVolatile(smb, tf)/(Pnt*_Pnt),1)+" ?.";
MqlDateTime mdt; datetime dt=TimeCurrent(mdt);
t++; txt[t]="????????: "+((dt-fdtBid)>0?DTS(nBid*1.0/(dt-fdtBid),2):"0");
Comment2(sID+"vi.", t+1, txt, clr, 1, 10, y);
y+=20;
}
double CountVBalance()
{
string name[]; int n=SelectGV(sID+"VOrder.", name);
double bal=0;
for (int i=0; i<n; i++)
{
string sid=StringSubstr(name[i], StringLen(sID+"VOrder."));
int dir=(int)GetGV(name[i]); // ??? ????????????
if (dir==OP_BALANCE) { bal+=GetGV(sID+"VO."+sid+".prof"); continue; } // ???? ?????????? ?????
if (!CheckGV(sID+"VO."+sid+".cl")) continue;
bal+=CalcProf(dir, GetGV(sID+"VO."+sid+".op"), GetGV(sID+"VO."+sid+".cl"), GetGV(sID+"VO."+sid+".lot"));
}
return(bal);
}
void RealInfo(int SysID, string smb, int &y)
{
if (!bRealInfo) return;
string txt[100]; int t=-1; color clr[100]; ArrayInitialize(clr, clrLightGray);
t++; txt[t]="========== REAL ========="; clr[t]=clrGray;
int ticketO[]; int no=GetTickets(-1, SysID, smb, ticketO);
int ticketH[]; int nh=GetTicketsH(-1, SysID, smb, ticketH);
int cdir=-1, cticket=0; double cop=0, cprof=0, cpprof=0, apr=0;
int comp=0; double pcomp=0;
for (int i=0; i<no; i++)
{
if (!OrderSelect(ticketO[i], SELECT_BY_TICKET)) continue;
cticket=OrderTicket(); cdir=OrderType();
cop=OrderOpenPrice(); cprof=OrderProfit(); cpprof=(OrderClosePrice()-OrderOpenPrice())*SD(cdir);
apr=APR(cdir);
int c=StringFind(OrderComment(), "|"); if (c>0) { int p=STI(StringSubstr(OrderComment(), c+1)); comp+=p; pcomp+=CalcProf(0, 0, p*Pnt*_Pnt, OrderLots()); }
t++; txt[t]=OTS(cdir)+"#"+ITS(cticket)+" | "+DTS(cop)+" | "+DTS(apr)+" | "+DTS(cpprof/(Pnt*_Pnt),0)+"?. | "+DTS(cprof,2)+"$"; clr[t]=OTC(cdir);
}
double prof=0, loss=0, pprof=0, ploss=0; int nb=0, ns=0;
for (int i=0; i<nh; i++)
{
if (!OrderSelect(ticketH[i], SELECT_BY_TICKET)) continue;
int c=StringFind(OrderComment(), "|"); if (c<0) continue;
int p=STI(StringSubstr(OrderComment(), c+1)); comp+=p; pcomp+=CalcProf(0, 0, p*Pnt*_Pnt, OrderLots());
if (OrderProfit()>=0) { prof+=OrderProfit(); pprof+=(OrderClosePrice()-OrderOpenPrice())*SD(OrderType()); }
else { loss+=OrderProfit(); ploss+=(OrderClosePrice()-OrderOpenPrice())*SD(OrderType()); }
if (OrderType()==OP_BUY) nb++; else ns++;
}
if (cdir<0) { t++; txt[t]="???????? ???????: ???"; }
t++; txt[t]="?????????";
t++; txt[t]="???????? ???????: Sell "+ITS(ns)+" | Buy "+ITS(nb);
t++; txt[t]="???????: "+DTS(pprof/(Показано первые 50% кода (символов: 45863)
Открыть по тарифу
Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.
Разовая покупка файла
На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.
Зачем нужен email? После подтверждения оплаты файл сохранится в кабинете на этот email. Если аккаунта ещё нет, мы создадим его и пришлём ссылку для задания пароля. Если аккаунт уже есть, покупка добавится в него. Укажите адрес, к которому у вас есть доступ.
Чтобы оформить заказ, введите email и перейдите к оплате.