MQL4: полезные функции пишем сюда

Тема в разделе "Индикаторы, скрипты и эксперты для МТ4", создана пользователем RickD, 5 июн 2006.

  1. finger

    finger Alex

    <b>isWeekend()</b>

    Return TRUE if Weekend :bs:

    <!--c1--><div class='codetop'>Код</div><div class='codemain'><!--ec1-->bool isWeekend()
    &nbsp;&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp; int DoW = TimeDayOfWeek(TimeLocal());
    &nbsp;&nbsp; if(DoW == 0 || DoW == 6 ) return(True);
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return(False);
    &nbsp;&nbsp;}<!--c2--></div><!--ec2-->


    <b>
    example:
    </b>
    <!--c1--><div class='codetop'>Код</div><div class='codemain'><!--ec1-->int Start() {

    if(isWeekend()) {Comment("great Weekend!"); return(0);}

    }<!--c2--></div><!--ec2-->
     
  2. finger

    finger Alex

    <b>
    return value is <u>If</u> true.... by RickD</b> :az:

    <!--c1--><div class='codetop'>Код</div><div class='codemain'><!--ec1-->double If(bool cond, double if_true, double if_false)
    {
    &nbsp;&nbsp;if (cond) return (if_true);
    &nbsp;&nbsp;return (if_false);
    }<!--c2--></div><!--ec2-->



    <b>example</b>
    <!--c1--><div class='codetop'>Код</div><div class='codemain'><!--ec1-->extern int StopLoss = 70;
    extern int TakeProfit = 120;

    int start()
    {
    &nbsp;&nbsp;

    &nbsp;&nbsp; double price, sl, tp;
    &nbsp;&nbsp; price = Bid;
    &nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp;sl = If(StopLoss > 0, price + StopLoss*Point, 0);
    &nbsp;&nbsp;&nbsp;&nbsp;tp = If(TakeProfit > 0, price - TakeProfit*Point, 0);

    }<!--c2--></div><!--ec2-->

    :tatice_06: Я люблю эту функцию :tatice_06:
    Вы имеете больше?
     
  3. RickD

    RickD MQL4 developer

    Naturlich! :cj:
     
  4. finger

    finger Alex

    ...И что, если мы нуждаемся в нескольких ценностях различных типов, которые будут возвращены одновременно?
    Смотрите здесь:

    <!--c1--><div class='codetop'>Код</div><div class='codemain'><!--ec1-->void SuperFunc(int& valueForReturn1,double& valueForReturn2,string& valueForReturn3)
    {
    &nbsp;&nbsp; valueForReturn1=100;
    &nbsp;&nbsp; valueForReturn2=300.0;
    &nbsp;&nbsp; valueForReturn3="it works!!";
    }<!--c2--></div><!--ec2-->

    <b>example:</b>
    <!--c1--><div class='codetop'>Код</div><div class='codemain'><!--ec1-->int value1=0;
    double value2=0.0;
    string value3="";

    SuperFunc(value1,value2,value3);
    MessageBox("value1="+value1+" value2="+value2+" value3="+value3);<!--c2--></div><!--ec2-->
     
  5. finger

    finger Alex

    Is BAR End ?


    <!--c1--><div class='codetop'>Код</div><div class='codemain'><!--ec1-->bool IsBarEnd()
    {
    &nbsp;&nbsp;&nbsp;&nbsp;bool bIsBarEnd = false;
    &nbsp;&nbsp;&nbsp;&nbsp;if(nBars != Bars)
    &nbsp;&nbsp;&nbsp;&nbsp;{
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;bIsBarEnd = true;
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;nBars = Bars;
    &nbsp;&nbsp;&nbsp;&nbsp;}
    &nbsp;&nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp;return(bIsBarEnd);
    }<!--c2--></div><!--ec2-->


    <b>example:</b>
    <!--c1--><div class='codetop'>Код</div><div class='codemain'><!--ec1--> if(!IsBarEnd())
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return(0);<!--c2--></div><!--ec2-->
     
  6. finger

    finger Alex

    Anybody tried out Larry Williams MM formula as described in his book "Long-Term Secrets for Short-Term Trading"?

    (Account Balance x Risk Percentage) / largest loss.

    Helps control drawdown while simultaneously allowing safer compounding. He says that once you get over 13% on the risk percentage, "...drawdown increases faster than the increases in profit."

    <b>Function LarryWiliamsMM()</b>

    <!--c1--><div class='codetop'>Код</div><div class='codemain'><!--ec1-->double LarryWiliamsMM()
    {
    &nbsp;&nbsp; double LargestLoss = 1;
    &nbsp;&nbsp; double Lot = LotStep;
    &nbsp;&nbsp;
    &nbsp;&nbsp; double PipValue = MarketInfo(Symbol(),MODE_TICKVALUE);
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp; int totalH = OrdersHistoryTotal();
    &nbsp;&nbsp; for(int cntH = 0; cntH<=totalH; cntH++)
    &nbsp;&nbsp; {
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;OrderSelect(cntH, SELECT_BY_POS, MODE_HISTORY);

    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if(OrderMagicNumber() == getMagic())
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if(OrderProfit() < 0 && OrderProfit() < LargestLoss)
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; LargestLoss = OrderProfit();
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;
    &nbsp;&nbsp; }
    &nbsp;&nbsp;
    &nbsp;&nbsp; Lot = ((AccountBalance()*LWMMRisk)/MathAbs(LargestLoss))/(10000*PipValue);&nbsp;&nbsp;
    &nbsp;&nbsp;
    &nbsp;&nbsp; if (Lot > MaxLots){ Lot = MaxLots; }
    &nbsp;&nbsp; if (Lot < MinLots){ Lot = MinLots; }

    &nbsp;&nbsp; return(Lot);
    }<!--c2--></div><!--ec2-->

    ^drink
     
  7. EvgenO

    EvgenO Новичок

    Народ, помогите написать скрипт по типу Trailing Stop, но только чтоб он при достижении определенной прибыли переводил SL в безубыток и все... Заранее благодарен всем кто возмется помочь.. ^drink
     
  8. finger

    finger Alex

    @RickD you have new полезные функции ? :cv:
     
  9. finger

    finger Alex

    new Update

    MoneyManagement by L.Williams
    Anybody tried out Larry Williams MM formula as described in his book "Long-Term Secrets for Short-Term Trading"

    (Account Balance x Risk Percentage) / largest loss.

    Helps control drawdown while simultaneously allowing safer compounding. He says that once you get over 13% on the risk percentage, "...drawdown increases faster than the increases in profit."


    <!--c1--><div class='codetop'>Код</div><div class='codemain'><!--ec1-->extern double&nbsp;&nbsp;&nbsp;&nbsp; Lots&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=&nbsp;&nbsp; 1;
    extern double&nbsp;&nbsp;&nbsp;&nbsp; MMRisk&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; =&nbsp;&nbsp;0.05;&nbsp;&nbsp;// Risk Factor
    extern double&nbsp;&nbsp;&nbsp;&nbsp; LossMax&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=&nbsp;&nbsp;3200;&nbsp;&nbsp;// Maximum Loss by 1 Lot

    void start()
    {

    double Lotsi = MoneyManagement (Lots, MMRisk, LossMax);

    }


    //----------------------------------------------------------------

    double MoneyManagement (double Lots, double risk, double maxloss)
    {
    &nbsp;&nbsp; double MinLots=NormalizeDouble(MarketInfo(Symbol(),23),2);
    &nbsp;&nbsp; double LotStep=NormalizeDouble(MarketInfo(Symbol(),24),2);
    &nbsp;&nbsp; double MaxLots=NormalizeDouble(MarketInfo(Symbol(),25),2);
    &nbsp;&nbsp; int LotDigit;
    &nbsp;&nbsp; if (LotStep==1) { LotDigit=0; }
    &nbsp;&nbsp; if (LotStep==0.1) { LotDigit=1; }
    &nbsp;&nbsp; if (LotStep==0.01) { LotDigit=2; }
    &nbsp;&nbsp; double Lotsi=Lots;
    &nbsp;&nbsp; double MAXloss=maxloss;
    &nbsp;&nbsp; Lotsi=NormalizeDouble(Lots*AccountEquity()*risk/MAXloss,LotDigit);&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp; if (Lotsi<MinLots) Lotsi=MinLots;
    &nbsp;&nbsp; if (Lotsi>MaxLots) Lotsi=MaxLots;&nbsp;&nbsp;
    &nbsp;&nbsp; return(Lotsi);
    }<!--c2--></div><!--ec2-->
     
  10. RickD

    RickD MQL4 developer

    <!--QuoteBegin-golden188+--> <table border="0" cellpadding="0" cellspacing="0" width="90%" align="center"> <tr> <td class="vbquote"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td class="vbquote" width="75" valign="bottom"> <table border="0" cellpadding="0" cellspacing="0" width="50px"> <tr> <td class="vbquote" width="28" valign="top"><img src="/forum/style_images/<#IMG_DIR#>/quotes/quot-top-left.gif" alt="" /></td> <td class="vbquote" width="100%" style="background-image: url('/forum/style_images/<#IMG_DIR#>/quotes/quote-bg.gif'); background-position: center;" valign="middle"><span class="vbquote">Цитата:</span></td> <td class="vbquote" valign="top"><img src="/forum/style_images/<#IMG_DIR#>/quotes/quot-top-right.gif" alt="" /></td> </tr> </table> </td> <td class="vbquote" align="left" style="background-image: url('/forum/style_images/<#IMG_DIR#>/quotes/quot-lr-bg.gif')" valign="bottom"></td><td class="vbquote" width="0" align="left" valign="bottom"> <table border="0" cellpadding="0" cellspacing="0" width="200"> <tr> <td class="vbquote" valign="top"><img src="/forum/style_images/<#IMG_DIR#>/quotes/quot-by-left.gif" alt="" /></td> <td class="vbquote" width="100%" style="background-image: url('/forum/style_images/<#IMG_DIR#>/quotes/quot-bye-bg.gif')" align="left" valign="middle" nowrap="nowrap"><span class="vbquote">(golden188)</span></td> <td class="vbquote" valign="top"><img src="/forum/style_images/<#IMG_DIR#>/quotes/quot-by-right.gif" alt="" /></td> </tr> </table> </td><td class="vbquote" width="100%" align="right" valign="bottom"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td class="vbquote" width="100%"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td class="vbquote" style="background-image: url('/forum/style_images/<#IMG_DIR#>/quotes/quot-top-bg.gif')" width="100%" valign="middle"></td> <td class="vbquote" align="left" valign="top"><img src="/forum/style_images/<#IMG_DIR#>/quotes/quot-top-right-10.gif" alt="" /></td> </tr> </table> </td> </tr> </table> </td> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td class="vbquote" width="10" style="background-image: url('/forum/style_images/<#IMG_DIR#>/quotes/quoting-left.gif')"></td> <td class="vbquotemain" width="100%" valign="top"></td> <td class="vbquote" width="10" style="background-image: url('/forum/style_images/<#IMG_DIR#>/quotes/quoting-right.gif')"></td> </tr> <tr> <td class="vbquote" width="10" style="background-image: url('/forum/style_images/<#IMG_DIR#>/quotes/quot-left-bg.gif')"></td> <td class="vbquotemain" width="100%" valign="top"><i><!--QuoteEBegin-->Could someone please help me with some language to make my Expert Advisor trade a percentage of my balance? For example, I would like each trade, instead of being x number of lots, to be 10% of my current balance. Does anyone know how to do this? The more explicit the details the more helpful it would be.

    thanks.<!--QuoteEnd--></i></td> <td class="vbquote" width="10" style="background-image: url('/forum/style_images/<#IMG_DIR#>/quotes/quot-right-bg.gif')"></td> </tr> <tr> <td class="vbquote" width="10" valign="bottom"><img src="/forum/style_images/<#IMG_DIR#>/quotes/quot-bot-left.gif" alt="" /></td> <td class="vbquote" width="100%" style="background-image: url('/forum/style_images/<#IMG_DIR#>/quotes/quot-bot-bg.gif')"></td> <td class="vbquote" width="10" valign="bottom"><img src="/forum/style_images/<#IMG_DIR#>/quotes/quot-bot-right.gif" alt="" /></td> </tr> </table> </td> </tr> </table><!--QuoteEEnd-->

    Для расчета лота как % от баланса можно воспользоваться следующей функцией:

    <!--c1--><div class='codetop'>Код</div><div class='codemain'><!--ec1-->extern double Lots = 0.1;
    extern double MinLot = 0.1;
    extern double MaxLot = 5.0;
    extern int LotPrec = 1;
    extern bool DynamicLot = false;
    extern double LotStep = 0.1;
    extern double BalanceStep = 500;

    double GetLots()
    {
    &nbsp;&nbsp;double lots = Lots;

    &nbsp;&nbsp;if (DynamicLot)
    &nbsp;&nbsp;{
    &nbsp;&nbsp;&nbsp;&nbsp;lots = NormalizeDouble(LotStep*AccountBalance()/BalanceStep, LotPrec);&nbsp;&nbsp;
    &nbsp;&nbsp;}

    &nbsp;&nbsp;lots = MathMax(lots, MinLot);
    &nbsp;&nbsp;lots = MathMin(lots, MaxLot);
    &nbsp;&nbsp;return (lots);
    }<!--c2--></div><!--ec2-->
     
  11. finger

    finger Alex

    request

    PC Show Down
    with Mql4 and Dll ?
     
  12. finger

    finger Alex

    Get MetaTrader progam directory with MQL4+WIN-API

    is possible?
     
  13. finger

    finger Alex


    yes use MQL4 Function TerminalPath()

    <!--c1--><div class='codetop'>Код</div><div class='codemain'><!--ec1-->Print("Working directory is ",TerminalPath());<!--c2--></div><!--ec2-->
     
  14. finger

    finger Alex

    Thanks :)
     
  15. finger

    finger Alex

    --

    Function StringLower() by KimIV
    change String Upper to String Lower

    <!--c1--><div class='codetop'>Код</div><div class='codemain'><!--ec1-->string StringLower(string s) {
    &nbsp;&nbsp;int c, i, k=StringLen(s), n;
    &nbsp;&nbsp;for (i=0; i<k; i++) {
    &nbsp;&nbsp;&nbsp;&nbsp;n=0;
    &nbsp;&nbsp;&nbsp;&nbsp;c=StringGetChar(s, i);
    &nbsp;&nbsp;&nbsp;&nbsp;if (c>64 && c<91) n=c+32;&nbsp;&nbsp;&nbsp;&nbsp; // A-Z -> a-z
    &nbsp;&nbsp;&nbsp;&nbsp;if (c>191 && c<224) n=c+32;&nbsp;&nbsp; // À-ß -> à-ÿ
    &nbsp;&nbsp;&nbsp;&nbsp;if (c==168) n=184;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;&nbsp;¨&nbsp;&nbsp;->&nbsp;&nbsp;¸
    &nbsp;&nbsp;&nbsp;&nbsp;if (n>0) s=StringSetChar(s, i, n);
    &nbsp;&nbsp;}
    &nbsp;&nbsp;return(s);
    }<!--c2--></div><!--ec2-->


    Example
    <!--c1--><div class='codetop'>Код</div><div class='codemain'><!--ec1-->Print(StringLower(Symbol());<!--c2--></div><!--ec2-->


    --
     
  16. Sasha83

    Sasha83 Новичок

    Доброго времени суток!!!
    Помогите есть идея но для дальнейшей реализации не хватает самой малости.
    Нужен индюк или код который бы показывал угол наклона (в градусах) МА к горизонтали.
    Если есть уже такой скиньте плиз или хотя бы ссылочку.
    !!!!!ПЛИЗ!!!!!
     
  17. finger

    finger Alex

    How to get the angle of a moving average
    <span class='inv'><![CDATA[<noindex>]]></span><a href="http://www.onix-trade.net/forum/go.php?http://forum.mql4.com/5672/page2" rel="nofollow" target="_blank">http://forum.mql4.com/5672/page2</a><span class='inv'><![CDATA[</noindex>]]></span>
     
  18. finger

    finger Alex

    <b>ShowDirectory</b>


    <!--c1--><div class='codetop'>Код</div><div class='codemain'><!--ec1-->#define SW_SHOW&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;5

    #import "shell32.dll"
    int ShellExecuteA(int hWnd,int lpVerb,string lpFile,int lpParameters,int lpDirectory,int nCmdShow);
    #import

    void ShowDirectory(string path)
    {
    int err;

    err=ShellExecuteA(0,"Open",path,0,0,SW_SHOW);
    if(err<32)Print("ShellExecuteA error(",err,")" );
    }<!--c2--></div><!--ec2-->


    <b>example</b>
    <!--c1--><div class='codetop'>Код</div><div class='codemain'><!--ec1-->#property copyright ""
    #property link&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;""

    #define SW_SHOW&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;5

    #import "shell32.dll"
    int ShellExecuteA(int hWnd,int lpVerb,string lpFile,int lpParameters,int lpDirectory,int nCmdShow);
    #import

    #include <WinUser32.mqh>

    int start()
    {
    &nbsp;&nbsp;
    &nbsp;&nbsp;if(IsDllsAllowed()==false)
    &nbsp;&nbsp;&nbsp;&nbsp;{
    &nbsp;&nbsp;&nbsp;&nbsp; Alert("Script gestoppt. DLL Unterstützung ist deaktiviert.");
    &nbsp;&nbsp;&nbsp;&nbsp; return(0);
    &nbsp;&nbsp;&nbsp;&nbsp;}
    ShowDirectory(TerminalPath()+"\expert\files");

    return(0);
    }

    void ShowDirectory(string path)
    {
    int err;

    err=ShellExecuteA(0,"Open",path,0,0,SW_SHOW);
    if(err<32)Print("ShellExecuteA error(",err,")" );
    }<!--c2--></div><!--ec2-->
     
  19. Sasha83

    Sasha83 Новичок

    Огромнейшее спасибо!!!! :tatice_06:
    Будемс разбираться!!! ^edkk^
     
  20. Herkules

    Herkules Новичок

    Всем привет и с Новым Годом !
    На днях скачал робота, запустил его на тесте, а он торгует в обратную сторону...заглянул ему под "капот", а там ...

    void ExternalParametersCheck() {
    if (Slippage > 10) {
    Comment("... Задано слишком высокое значение проскальзывания Slippage,",
    "\n", "... Скорректируйте чтобы было не более 10п и перезапустите эксперт.");
    return;
    }
    if (Warp > 100 || Warp < -100) {
    Comment("... Неправильно задан параметр искажения Warp,",
    "\n", "... Диапазон допустимых значений от -100 до +100 с шагом 1,",
    "\n", "... Скорректируйте и перезапустите эксперт.");
    return;
    }
    if (Deviation > 2.0 || Warp < 0) {
    Comment("... Неправильно задан параметр девиации Deviation,",
    "\n", "... Диапазон допустимых значений от 0 до +2 с шагом 0.01,",
    "\n", "... Скорректируйте и перезапустите эксперт.");
    return;
    }
    if (Amplitude > 200 || Amplitude < 0) {
    Comment("... Неправильно задан параметр девиации Amplitude,",
    "\n", "... Диапазон допустимых значений от 0 до +200 с шагом 1,",
    "\n", "... Скорректируйте и перезапустите эксперт.");
    return;
    }
    if (Distortion > 1.0 || Distortion < -1.0) {
    Comment("... Неправильно задан параметр девиации Distortion,",
    "\n", "... Диапазон допустимых значений от -1 до +1 с шагом 0.01,",
    "\n", "... Скорректируйте и перезапустите эксперт.");
    return;
    }
    }

    что исправить и как это должно быть ...? помогите запустить робота !!
     

Поделиться этой страницей