DAILY BREAKOUT a little coding help

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #7222 quote
    Robert975Robert975
    Participant
    Junior

    I have code made in EA Builder for a DAILY BREAKOUT. This code is only for MT4

    How do i say this in PRT

    Price crosses above Ressistance and Price crosses under Support?

    And a time interval 12.00 hours

     

    Greets

     

    Robert

     

    //+——————————————————————+
    //|                                 Strategy: Daily Breakout 1.0.mq4 |
    //|                                       Created with EABuilder.com |
    //|                                             http://eabuilder.com |
    //+——————————————————————+
    #property copyright “Created with EABuilder.com”
    #property link      “http://eabuilder.com”
    #property version   “1.00”
    #property description “”
    #include <stdlib.mqh>
    #include <stderror.mqh>
    int LotDigits; //initialized in OnInit
    int MagicNumber = 401652;
    int NextOpenTradeAfterTOD_Hour = 10; //next open trade after time of the day
    int NextOpenTradeAfterTOD_Min = 00; //next open trade after time of the day
    datetime NextTradeTime = 0;
    extern double TradeSize = 0.01;
    int MaxSlippage = 3; //adjusted in OnInit
    bool crossed[2]; //initialized to true, used in function Cross
    extern bool Audible_Alerts = true;
    int MaxOpenTrades = 1000;
    int MaxLongTrades = 1000;
    int MaxShortTrades = 1000;
    int MaxPendingOrders = 1000;
    bool Hedging = true;
    int OrderRetry = 5; //# of retries if sending order returns error
    int OrderWait = 5; //# of seconds to wait if sending order returns error
    double myPoint; //initialized in OnInit
    //— Custom functions ———————————————–
    double ExampleFunction()
    {
    return(High[1] – Low[1]);
    }
    //— End of custom functions —————————————-
    bool Cross(int i, bool condition) //returns true if “condition” is true and was false in the previous call
    {
    bool ret = condition && !crossed[i];
    crossed[i] = condition;
    return(ret);
    }
    void myAlert(string type, string message)
    {
    if(type == “print”)
    Print(message);
    else if(type == “error”)
    {
    Print(type+” | Daily Breakout 1.0 @ “+Symbol()+”,”+Period()+” | “+message);
    if(Audible_Alerts) Alert(type+” | Daily Breakout 1.0 @ “+Symbol()+”,”+Period()+” | “+message);
    }
    else if(type == “order”)
    {
    if(Audible_Alerts) Alert(type+” | Daily Breakout 1.0 @ “+Symbol()+”,”+Period()+” | “+message);
    }
    else if(type == “modify”)
    {
    }
    }
    int TradesCount(int type) //returns # of open trades for order type, current symbol and magic number
    {
    int result = 0;
    int total = OrdersTotal();
    for(int i = 0; i < total; i++)
    {
    if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES) == false) continue;
    if(OrderMagicNumber() != MagicNumber || OrderSymbol() != Symbol() || OrderType() != type) continue;
    result++;
    }
    return(result);
    }
    int myOrderSend(int type, double price, double volume, string ordername) //send order, return ticket (“price” is irrelevant for market orders)
    {
    if(!IsTradeAllowed()) return(-1);
    int ticket = -1;
    int retries = 0;
    int err;
    int long_trades = TradesCount(OP_BUY);
    int short_trades = TradesCount(OP_SELL);
    int long_pending = TradesCount(OP_BUYLIMIT) + TradesCount(OP_BUYSTOP);
    int short_pending = TradesCount(OP_SELLLIMIT) + TradesCount(OP_SELLSTOP);
    string ordername_ = ordername;
    if(ordername != “”)
    ordername_ = “(“+ordername+”)”;
    //test Hedging
    if(!Hedging && ((type % 2 == 0 && short_trades + short_pending > 0) || (type % 2 == 1 && long_trades + long_pending > 0)))
    {
    myAlert(“print”, “Order”+ordername_+” not sent, hedging not allowed”);
    return(-1);
    }
    //test maximum trades
    if((type % 2 == 0 && long_trades >= MaxLongTrades)
    || (type % 2 == 1 && short_trades >= MaxShortTrades)
    || (long_trades + short_trades >= MaxOpenTrades)
    || (type > 1 && long_pending + short_pending >= MaxPendingOrders))
    {
    myAlert(“print”, “Order”+ordername_+” not sent, maximum reached”);
    return(-1);
    }
    //prepare to send order
    while(IsTradeContextBusy()) Sleep(100);
    RefreshRates();
    if(type == OP_BUY)
    price = Ask;
    else if(type == OP_SELL)
    price = Bid;
    else if(price < 0) //invalid price for pending order
    {
    myAlert(“order”, “Order”+ordername_+” not sent, invalid price for pending order”);
    return(-1);
    }
    int clr = (type % 2 == 1) ? clrRed : clrBlue;
    while(ticket < 0 && retries < OrderRetry+1)
    {
    ticket = OrderSend(Symbol(), type, NormalizeDouble(volume, LotDigits), NormalizeDouble(price, Digits()), MaxSlippage, 0, 0, ordername, MagicNumber, 0, clr);
    if(ticket < 0)
    {
    err = GetLastError();
    myAlert(“print”, “OrderSend”+ordername_+” error #”+err+” “+ErrorDescription(err));
    Sleep(OrderWait*1000);
    }
    retries++;
    }
    if(ticket < 0)
    {
    myAlert(“error”, “OrderSend”+ordername_+” failed “+(OrderRetry+1)+” times; error #”+err+” “+ErrorDescription(err));
    return(-1);
    }
    string typestr[6] = {“Buy”, “Sell”, “Buy Limit”, “Sell Limit”, “Buy Stop”, “Sell Stop”};
    myAlert(“order”, “Order sent”+ordername_+”: “+typestr[type]+” “+Symbol()+” Magic #”+MagicNumber);
    return(ticket);
    }
    int myOrderModify(int ticket, double SL, double TP) //modify SL and TP (absolute price), zero targets do not modify
    {
    if(!IsTradeAllowed()) return(-1);
    bool success = false;
    int retries = 0;
    int err;
    SL = NormalizeDouble(SL, Digits());
    TP = NormalizeDouble(TP, Digits());
    if(SL < 0) SL = 0;
    if(TP < 0) TP = 0;
    //prepare to select order
    while(IsTradeContextBusy()) Sleep(100);
    if(!OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES))
    {
    err = GetLastError();
    myAlert(“error”, “OrderSelect failed; error #”+err+” “+ErrorDescription(err));
    return(-1);
    }
    //prepare to modify order
    while(IsTradeContextBusy()) Sleep(100);
    RefreshRates();
    if(CompareDoubles(SL, 0)) SL = OrderStopLoss(); //not to modify
    if(CompareDoubles(TP, 0)) TP = OrderTakeProfit(); //not to modify
    if(CompareDoubles(SL, OrderStopLoss()) && CompareDoubles(TP, OrderTakeProfit())) return(0); //nothing to do
    while(!success && retries < OrderRetry+1)
    {
    success = OrderModify(ticket, NormalizeDouble(OrderOpenPrice(), Digits()), NormalizeDouble(SL, Digits()), NormalizeDouble(TP, Digits()), OrderExpiration(), CLR_NONE);
    if(!success)
    {
    err = GetLastError();
    myAlert(“print”, “OrderModify error #”+err+” “+ErrorDescription(err));
    Sleep(OrderWait*1000);
    }
    retries++;
    }
    if(!success)
    {
    myAlert(“error”, “OrderModify failed “+(OrderRetry+1)+” times; error #”+err+” “+ErrorDescription(err));
    return(-1);
    }
    string alertstr = “Order modified: ticket=”+ticket;
    if(!CompareDoubles(SL, 0)) alertstr = alertstr+” SL=”+SL;
    if(!CompareDoubles(TP, 0)) alertstr = alertstr+” TP=”+TP;
    myAlert(“modify”, alertstr);
    return(0);
    }
    int myOrderModifyRel(int ticket, double SL, double TP) //modify SL and TP (relative to open price), zero targets do not modify
    {
    if(!IsTradeAllowed()) return(-1);
    bool success = false;
    int retries = 0;
    int err;
    SL = NormalizeDouble(SL, Digits());
    TP = NormalizeDouble(TP, Digits());
    if(SL < 0) SL = 0;
    if(TP < 0) TP = 0;
    //prepare to select order
    while(IsTradeContextBusy()) Sleep(100);
    if(!OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES))
    {
    err = GetLastError();
    myAlert(“error”, “OrderSelect failed; error #”+err+” “+ErrorDescription(err));
    return(-1);
    }
    //prepare to modify order
    while(IsTradeContextBusy()) Sleep(100);
    RefreshRates();
    //convert relative to absolute
    if(OrderType() % 2 == 0) //buy
    {
    if(NormalizeDouble(SL, Digits()) != 0)
    SL = OrderOpenPrice() – SL;
    if(NormalizeDouble(TP, Digits()) != 0)
    TP = OrderOpenPrice() + TP;
    }
    else //sell
    {
    if(NormalizeDouble(SL, Digits()) != 0)
    SL = OrderOpenPrice() + SL;
    if(NormalizeDouble(TP, Digits()) != 0)
    TP = OrderOpenPrice() – TP;
    }
    if(CompareDoubles(SL, 0)) SL = OrderStopLoss(); //not to modify
    if(CompareDoubles(TP, 0)) TP = OrderTakeProfit(); //not to modify
    if(CompareDoubles(SL, OrderStopLoss()) && CompareDoubles(TP, OrderTakeProfit())) return(0); //nothing to do
    while(!success && retries < OrderRetry+1)
    {
    success = OrderModify(ticket, NormalizeDouble(OrderOpenPrice(), Digits()), NormalizeDouble(SL, Digits()), NormalizeDouble(TP, Digits()), OrderExpiration(), CLR_NONE);
    if(!success)
    {
    err = GetLastError();
    myAlert(“print”, “OrderModify error #”+err+” “+ErrorDescription(err));
    Sleep(OrderWait*1000);
    }
    retries++;
    }
    if(!success)
    {
    myAlert(“error”, “OrderModify failed “+(OrderRetry+1)+” times; error #”+err+” “+ErrorDescription(err));
    return(-1);
    }
    string alertstr = “Order modified: ticket=”+ticket;
    if(!CompareDoubles(SL, 0)) alertstr = alertstr+” SL=”+SL;
    if(!CompareDoubles(TP, 0)) alertstr = alertstr+” TP=”+TP;
    myAlert(“modify”, alertstr);
    return(0);
    }
    void DrawLine(string objname, double price, int count, int start_index) //creates or modifies existing object if necessary
    {
    if((price < 0) && ObjectFind(objname) >= 0)
    {
    ObjectDelete(objname);
    }
    else if(ObjectFind(objname) >= 0 && ObjectType(objname) == OBJ_TREND)
    {
    ObjectSet(objname, OBJPROP_TIME1, Time[start_index]);
    ObjectSet(objname, OBJPROP_PRICE1, price);
    ObjectSet(objname, OBJPROP_TIME2, Time[start_index+count-1]);
    ObjectSet(objname, OBJPROP_PRICE2, price);
    }
    else
    {
    ObjectCreate(objname, OBJ_TREND, 0, Time[start_index], price, Time[start_index+count-1], price);
    ObjectSet(objname, OBJPROP_RAY, false);
    ObjectSet(objname, OBJPROP_COLOR, C’0x00,0x00,0xFF’);
    ObjectSet(objname, OBJPROP_STYLE, STYLE_SOLID);
    ObjectSet(objname, OBJPROP_WIDTH, 2);
    }
    }
    double Support(int time_interval, bool fixed_tod, int hh, int mm, bool draw, int shift)
    {
    int start_index = shift;
    int count = time_interval / 60 / Period();
    if(fixed_tod)
    {
    datetime start_time;
    if(shift == 0)
    start_time = TimeCurrent();
    else
    start_time = Time[shift-1];
    datetime dt = StringToTime(StringConcatenate(TimeToString(start_time, TIME_DATE),” “,hh,”:”,mm)); //closest time hh:mm
    if (dt > start_time)
    dt -= 86400; //go 24 hours back
    int dt_index = iBarShift(NULL, 0, dt, true);
    datetime dt2 = dt;
    while(dt_index < 0 && dt > Time[Bars-1-count]) //bar not found => look a few days back
    {
    dt -= 86400; //go 24 hours back
    dt_index = iBarShift(NULL, 0, dt, true);
    }
    if (dt_index < 0) //still not found => find nearest bar
    dt_index = iBarShift(NULL, 0, dt2, false);
    start_index = dt_index + 1; //bar after S/R opens at dt
    }
    double ret = Low[iLowest(NULL, 0, MODE_LOW, count, start_index)];
    if (draw) DrawLine(“Support”, ret, count, start_index);
    return(ret);
    }
    double Resistance(int time_interval, bool fixed_tod, int hh, int mm, bool draw, int shift)
    {
    int start_index = shift;
    int count = time_interval / 60 / Period();
    if(fixed_tod)
    {
    datetime start_time;
    if(shift == 0)
    start_time = TimeCurrent();
    else
    start_time = Time[shift-1];
    datetime dt = StringToTime(StringConcatenate(TimeToString(start_time, TIME_DATE),” “,hh,”:”,mm)); //closest time hh:mm
    if (dt > start_time)
    dt -= 86400; //go 24 hours back
    int dt_index = iBarShift(NULL, 0, dt, true);
    datetime dt2 = dt;
    while(dt_index < 0 && dt > Time[Bars-1-count]) //bar not found => look a few days back
    {
    dt -= 86400; //go 24 hours back
    dt_index = iBarShift(NULL, 0, dt, true);
    }
    if (dt_index < 0) //still not found => find nearest bar
    dt_index = iBarShift(NULL, 0, dt2, false);
    start_index = dt_index + 1; //bar after S/R opens at dt
    }
    double ret = High[iHighest(NULL, 0, MODE_HIGH, count, start_index)];
    if (draw) DrawLine(“Resistance”, ret, count, start_index);
    return(ret);
    }
    void TrailingStopSet(int type, double price) //set Stop Loss at “price”
    {
    int total = OrdersTotal();
    for(int i = total-1; i >= 0; i–)
    {
    while(IsTradeContextBusy()) Sleep(100);
    if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
    if(OrderMagicNumber() != MagicNumber || OrderSymbol() != Symbol() || OrderType() != type) continue;
    myOrderModify(OrderTicket(), price, 0);
    }
    }
    bool NewBar()
    {
    static datetime LastTime = 0;
    bool ret = Time[0] > LastTime && LastTime > 0;
    LastTime = Time[0];
    return(ret);
    }
    //+——————————————————————+
    //| Expert initialization function                                   |
    //+——————————————————————+
    int OnInit()
    {
    //initialize myPoint
    myPoint = Point();
    if(Digits() == 5 || Digits() == 3)
    {
    myPoint *= 10;
    MaxSlippage *= 10;
    }
    //initialize LotDigits
    double LotStep = MarketInfo(Symbol(), MODE_LOTSTEP);
    if(LotStep >= 1) LotDigits = 0;
    else if(LotStep >= 0.1) LotDigits = 1;
    else if(LotStep >= 0.01) LotDigits = 2;
    else LotDigits = 3;
    NextTradeTime = 0;
    int i;
    //initialize crossed
    for (i = 0; i < ArraySize(crossed); i++)
    crossed[i] = true;
    return(INIT_SUCCEEDED);
    }
    //+——————————————————————+
    //| Expert deinitialization function                                 |
    //+——————————————————————+
    void OnDeinit(const int reason)
    {
    }
    //+——————————————————————+
    //| Expert tick function                                             |
    //+——————————————————————+
    void OnTick()
    {
    int ticket = -1;
    double price;
    double TP;
    bool isNewBar = NewBar();

    if(isNewBar) TrailingStopSet(OP_BUY, Support(12 * PeriodSeconds(), false, 00, 00, false, 0)); //Trailing Stop = Support
    if(isNewBar) TrailingStopSet(OP_SELL, Resistance(12 * PeriodSeconds(), false, 00, 00, false, 0)); //Trailing Stop = Resistance

    //Open Buy Order, instant signal is tested first
    RefreshRates();
    if(Cross(0, Bid > Resistance(12 * 3600, true, 10, 00, true, 0)) //Price crosses above Resistance
    )
    {
    RefreshRates();
    price = Ask;
    TP = 10 * myPoint; //Take Profit = value in points (relative to price)
    if(TimeCurrent() <= NextTradeTime) return; //next open trade after time of the day
    if(IsTradeAllowed())
    {
    ticket = myOrderSend(OP_BUY, price, TradeSize, “”);
    if(ticket <= 0) return;
    }
    else //not autotrading => only send alert
    myAlert(“order”, “”);
    NextTradeTime = StringToTime(IntegerToString(NextOpenTradeAfterTOD_Hour)+”:”+IntegerToString(NextOpenTradeAfterTOD_Min));
    while(NextTradeTime <= TimeCurrent()) NextTradeTime += 86400;
    myOrderModifyRel(ticket, 0, TP);
    }

    //Open Sell Order, instant signal is tested first
    RefreshRates();
    if(Cross(1, Bid < Support(12 * 3600, true, 10, 00, true, 0)) //Price crosses below Support
    )
    {
    RefreshRates();
    price = Bid;
    TP = 10 * myPoint; //Take Profit = value in points (relative to price)
    if(TimeCurrent() <= NextTradeTime) return; //next open trade after time of the day
    if(IsTradeAllowed())
    {
    ticket = myOrderSend(OP_SELL, price, TradeSize, “”);
    if(ticket <= 0) return;
    }
    else //not autotrading => only send alert
    myAlert(“order”, “”);
    NextTradeTime = StringToTime(IntegerToString(NextOpenTradeAfterTOD_Hour)+”:”+IntegerToString(NextOpenTradeAfterTOD_Min));
    while(NextTradeTime <= TimeCurrent()) NextTradeTime += 86400;
    myOrderModifyRel(ticket, 0, TP);
    }
    }
    //+——————————————————————+

    #7229 quote
    NicolasNicolas
    Keymaster
    Legend

    Yes this is a simple breakout strategy with a trailing stop based on recent support resistance. Have you tried code assisted creation?

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.
ProRealAI ProRealAI New

Stuck on this ProBuilder code?

Describe what this topic is trying to build, in plain English, and ProRealAI writes the ProRealTime™ indicator, screener or system for you.

Available in 7 languages
Try ProRealAI

DAILY BREAKOUT a little coding help


ProOrder: Automated Strategies & Backtesting

New Reply
Author
author-avatar
Robert975 @robert975 Participant
Summary

This topic contains 1 reply,
has 2 voices, and was last updated by NicolasNicolas
10 years, 4 months ago.

Topic Details
Forum: ProOrder: Automated Strategies & Backtesting
Language: English
Started: 05/17/2016
Status: Active
Attachments: No files
ProRealCode ProRealCode
Loading...