Jump to content

Open source FX Trading


Recommended Posts

I have gotten so much from this site that I decided to share my EA.

IF it is profitable for you, make a donation to an account I specify.

If you modify let me know so we can test it; and if its better than my method, credit will be given to the modder and I will not ask for any donation.

 

Logic of the ea ( ideally ): Calculate average ATR for 4 hour candles for currency of your choice for the previous year.

Attach EA to 1 hour chart

 

Caveat: I am too lazy to do this right now so if someone could get me a CSV file with live data it would be much appreciated.

 

Any questions feel free to ask.

 

I am not charging for this because you are not fools, I am not a scammer ( the website listed in the code is just for fun ), and KNOWLEDGE SHOULD BE SHARED FREELY.

 

STRANGE I COULD NOT ADD THE ATTACHMENT CODE FOLLOWS

 

//+------------------------------------------------------------------+
//|                                                     easycrom.mq4 |
//|                      Copyright © 2007, MetaQuotes Software Corp. |
//|                                        [url]http://www.metaquotes.net[/url] |
//+------------------------------------------------------------------+
#property copyright "Dominic Henry"
#property link      "www.*****.com"

int MagicNumber = 10000;
//extern double Range_ref =139;  // in points
extern double Lots = 0.1;  // in points
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
 {
//----
  
//----
  return(0);
 }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
 {
//----
  
//----
  return(0);
 }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
/*
I need help creating an EA that will in order
1) Calculate the difference between high and low of the last closed candle ( Range=Prev_CandleH - PrevCandleL)
2) Compare this value to a a variable
3) If the difference between high and low of the last closed candle is equal or greater than user assigned variable
4) Execute BUY STOP at LOW of prev candle and execute SELL STOP at LOW of prev candle 
5) Close pending order if not filled in 4 hours
6) Take profit of 40 pips



*/

int OrderCount(string symbol, int type)
{
  int count=0;
  for(int i=0;i<OrdersTotal();i++)
  {
     if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        continue;
     if(OrderSymbol()!=symbol)
        continue;
     if(OrderType()==type)
        count++;               
  }
  return(count);
}


double getRangeRef(string _symbol)
{  // this one a simple approach.
  // furthermore, when attaching the EA to a char
  // we can customize the external variables to the corresponding symbol.
  if(_symbol=="EURUSDm" || _symbol=="EURUSD")  // Attention here: depending on the broker's symbol, it can be EURUSD, eurusd, ... 
     return(100);         // EURUSDm, here is because my broker provides these symbols for minis.
  if(_symbol=="EURGBP" || _symbol=="EURGBP")  // Attention here: depending on the broker's symbol, it can be EURUSD, eurusd, ... 
     return(100);   
  if(_symbol=="USDJPYm" || _symbol=="USDJPY")  // Attention here: depending on the broker's symbol, it can be EURUSD, eurusd, ... 
     return(100);          // this could be specified in a  external file, or something like that.
  if(_symbol=="EURJPYm" || _symbol=="EURJPY")  // Attention here: depending on the broker's symbol, it can be EURUSD, eurusd, ... 
     return(100); 
  if(_symbol=="GBPJPYm" || _symbol=="GBPJPY")  // Attention here: depending on the broker's symbol, it can be EURUSD, eurusd, ... 
     return(100);       
  if(_symbol=="AUDUSDm" || _symbol=="AUDUSD")  // Attention here: depending on the broker's symbol, it can be EURUSD, eurusd, ... 
     return(100);          // this could be specified in a  external file, or something like that.   
  if(_symbol=="GBPUSDm" || _symbol=="GBPUSD")  // Attention here: depending on the broker's symbol, it can be EURUSD, eurusd, ... 
     return(100);           // this could be specified in a  external file, or something like that.   
  if(_symbol=="USDCADm" || _symbol=="USDCAD")  // Attention here: depending on the broker's symbol, it can be EURUSD, eurusd, ... 
     return(100);   
  if(_symbol=="USDCHFm" || _symbol=="USDCHF")  // Attention here: depending on the broker's symbol, it can be EURUSD, eurusd, ... 
     return(100);     
  //return(139); //default value provided to every other pairs.   
}


int start()
 {
     double Range = (High[1]-Low[1])/10;      
     
     double Range_ref=getRangeRef(Symbol());
     if( Range>= Range_ref*Point) {
        int digits              =  MarketInfo(Symbol(),MODE_DIGITS);         
        double buy_price        =  NormalizeDouble(High[1]         , digits);
        double sell_price       =  NormalizeDouble(Low[1]          , digits);
        double buy_take_profit  =  NormalizeDouble(High[1]+400*Point, digits);
        double sell_take_profit =  NormalizeDouble(Low[1]-400*Point, digits);
        int ticket=0;
        
        // if orderstotal is huge number, we could spare time here.
        int longOrders  = OrderCount(Symbol(),OP_BUYSTOP)+OrderCount(Symbol(),OP_BUY);
        int shortOrders = OrderCount(Symbol(),OP_SELLSTOP)+OrderCount(Symbol(),OP_SELL);  
        
        if(longOrders==0)
        if(buy_price > Ask)  //buy stop must be above market price
        ticket=OrderSend(Symbol(),OP_BUYSTOP,Lots, buy_price,3,0,buy_take_profit,"--",MagicNumber,TimeCurrent()+4*60*60,Green);
        if(ticket==-1)
           Print("error buystop = ", GetLastError());
           
        ticket=0;   
        if(shortOrders==0)
        if(sell_price<Bid) //sell stop must be below market price
        ticket = OrderSend(Symbol(),OP_SELLSTOP,Lots,sell_price,3,0,sell_take_profit,"--",MagicNumber,TimeCurrent()+4*60*60,Red);
        if(ticket==-1)
           Print("error sellstop = ", GetLastError());
     }         
     return(0);
 }
//+------------------------------------------------------------------+

-edited. if you like to share your code. its better if you add "code" on it.

-and. you can have .hist or csv on this site

www.alpari.com

 

K

Link to comment
Share on other sites

Re: Open source FX Trading

 

You are welcome, the backtest results for 2008 for GBPUSD and EURUSD using 20:1 leverage are good, 5k to 13k for GBPUSD and 5k to 17k for EURUSD. I just want someone to forward test it, as I have heard that demo prices are smoothed.

Also a weakness of this system is that it uses no stop loss so implement your own money management rules.

Link to comment
Share on other sites

  • 1 month later...
  • 2 weeks later...

Re: Open source FX Trading

 

Double trades? Hmm... I haven't read your EA throughly but I think the problem is one of these:

- when a condition is fulfilled, you need to check if it won't be entered again in the same candle. Because usually in the same candle / bar, when the tick is changed you get entered multiple times, coz the condition would be the same. Normally we solve this by entering the trade only if the volume is zero. So, put something like (if volume=0 {do trade} else {no trade})

 

- another more versatile solution would be to create a flag to check if the trade is positive or not.

 

Regards,

Ore no Shinka Hikari yo Hayai. Zen Uchi o Nani no Mono Ore no Shinka Chuito Kore Nai.

Ten no Michi yo Iki. Subete o Sukosadoru Otoko.

Link to comment
Share on other sites

Re: Open source FX Trading

 

I would opt for the more versatile solution but I honest have no idea how to implement it, and what is worse the EA works pretty well except for the multiple trades. Sometimes the multiple trades end in multiple profits but I like the idea of taking my money once and thats it.

Link to comment
Share on other sites

Re: Open source FX Trading

 

if (profit) {do trade} else {no trade}

 

how to check profit? Try this

// put the if inside the [OrderSelect] loop
if (TP_Reached(OP_BUY,OrderOpenPrice())==true){/* do trade */}

bool TP_Reached(int cmd,double OP){

  bool isReached=false;

  if(TP!=0){

     if ((cmd==OP_BUY) && (Bid >= OP + TP*Point))isReached=true;

     else if ((cmd==OP_SELL) && (Ask <= OP - TP*Point))isReached=true;

  }

  return(isReached);

}

 

You can then put flags anywhere you want.

 

Regards,

Ore no Shinka Hikari yo Hayai. Zen Uchi o Nani no Mono Ore no Shinka Chuito Kore Nai.

Ten no Michi yo Iki. Subete o Sukosadoru Otoko.

Link to comment
Share on other sites

Re: Open source FX Trading

 

You can then put flags anywhere you want.

 

Regards,

 

Hi william, what do you mean by put flags anywhere you want? sorry i'm not familiar with robots....thanks easycrom for sharing... :shand:

Well, flags are basically a programming technique, not just specific to EA or mql. So we can use flags anywhere. It's simple to understand and do but needs quite a long explanation to understand. Try googling "programming flag" without quotes.

 

Regards,

Ore no Shinka Hikari yo Hayai. Zen Uchi o Nani no Mono Ore no Shinka Chuito Kore Nai.

Ten no Michi yo Iki. Subete o Sukosadoru Otoko.

Link to comment
Share on other sites

Re: Open source FX Trading

 

I dont know enough about programming to understand that code :( but I will give away the way I use this system manually

 

Once I see the setup, I place the orders with an expiry of 24 hours.

 

If the trade is profitable 24 hours later I trade in the opposite direction. Now for my least favourite part, if the trade goes against me to the point that it reaches the other end of the set up bar, I double my order and trade in the opposite direction with a trailing stop of 100.

 

Now I have blown up several accounts using this method and 20:1 leverage per trade per currency, not one ended in me not being able to draw out my initial investement and a 10% profit though, but CLEARLY it needs improvement, and you can implement whatever stop losses you deem.

 

The backtesting is heartbreaking as the current robot can double your account but ALWAYS ENDS UP IN A MARGIN CALL.

 

A friend of mine recommended that I go long 10 pips above the high/low with a target of 100 pips and a stop loss of 50 pips.

 

So there you have it, wishing you profitable trades.

Link to comment
Share on other sites

  • 3 months later...

Re: Open source FX Trading

 

Maybe checking the bars from last trade and adding a time limit between orders...

I've made that for and EA of mine some time ago to limit it trading after a loss, so the EA waits X days far from last lost.

You can search in history for the last closed trade with your MagicNumber and if OrderCloseTime()+(offset time between orders you like) > TimeCurrent() then it's able to enter another order. else, wait.

 

To check last trade time i suggest this:

double CheckLastOrderTime(){

if (OrdersHistoryTotal()>0){

OrderSelect(OrdersHistoryTotal()-1,SELECT_BY_POS,MODE_HISTORY);

if (OrderMagicNumber()==MagicNumber){return(OrderCloseTime());}

}else {return(-1);}

 

}

 

If this function returns -1 then that means that the EA is able to trade, also, it's able to trade if CheckLastOrderTime()+(delayBetweenOrders)>TimeCurrent(). Else, don't trade.

 

EDIT: delayBetweenOrders should be the numbers of seconds you would like the EA to wait, you can multiply this by 3600 to use hours and so on...

Hope i can give you some help on it.

I'm out of time but if you don't get it i'll try later.

Regards.

Link to comment
Share on other sites

Re: Open source FX Trading

 

Hi,

 

I have added code to check if trade open and if true will not open new order.

 

Aslo added Money Management.

 

my code is between the /////////////////////// lines

hope this helps.

 

//+------------------------------------------------------------------+
//|                                                     easycrom.mq4 |
//|                      Copyright © 2007, MetaQuotes Software Corp. |
//|                                        [url]http://www.metaquotes.net[/url] |
//+------------------------------------------------------------------+
#property copyright "Dominic Henry"
#property link      "www.*****.com"

int MagicNumber = 10000;
//extern double Range_ref =139;  // in points
///////////////////////////////////////////////////////////////////////////
extern string     Account_Settings     = "-= Account Settings =-";
extern bool       UseMoneyManagement   =  true;
extern int        MinRisk              =  10;
extern string     Lots_No_MM           = "-= Lotsize if MM False =-";
extern double     LotSize              =  0.01;
//////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////
bool Buyfound=false,Sellfound=false;
///////////////////////////////////////////////////


//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
 {
//----
  
//----
  return(0);
 }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
 {
//----
  
//----
  return(0);
 }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
/*
I need help creating an EA that will in order
1) Calculate the difference between high and low of the last closed candle ( Range=Prev_CandleH - PrevCandleL)
2) Compare this value to a a variable
3) If the difference between high and low of the last closed candle is equal or greater than user assigned variable
4) Execute BUY STOP at LOW of prev candle and execute SELL STOP at LOW of prev candle
5) Close pending order if not filled in 4 hours
6) Take profit of 40 pips



*/

int OrderCount(string symbol, int type)
{
  int count=0;
  for(int i=0;i<OrdersTotal();i++)
  {
     if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        continue;
     if(OrderSymbol()!=symbol)
        continue;
     if(OrderType()==type)
        count++;               
  }
  return(count);
}


double getRangeRef(string _symbol)
{  // this one a simple approach.
  // furthermore, when attaching the EA to a char
  // we can customize the external variables to the corresponding symbol.
  if(_symbol=="EURUSDm" || _symbol=="EURUSD")  // Attention here: depending on the broker's symbol, it can be EURUSD, eurusd, ...
     return(100);         // EURUSDm, here is because my broker provides these symbols for minis.
  if(_symbol=="EURGBP" || _symbol=="EURGBP")  // Attention here: depending on the broker's symbol, it can be EURUSD, eurusd, ...
     return(100);   
  if(_symbol=="USDJPYm" || _symbol=="USDJPY")  // Attention here: depending on the broker's symbol, it can be EURUSD, eurusd, ...
     return(100);          // this could be specified in a  external file, or something like that.
  if(_symbol=="EURJPYm" || _symbol=="EURJPY")  // Attention here: depending on the broker's symbol, it can be EURUSD, eurusd, ...
     return(100);
  if(_symbol=="GBPJPYm" || _symbol=="GBPJPY")  // Attention here: depending on the broker's symbol, it can be EURUSD, eurusd, ...
     return(100);       
  if(_symbol=="AUDUSDm" || _symbol=="AUDUSD")  // Attention here: depending on the broker's symbol, it can be EURUSD, eurusd, ...
     return(100);          // this could be specified in a  external file, or something like that.   
  if(_symbol=="GBPUSDm" || _symbol=="GBPUSD")  // Attention here: depending on the broker's symbol, it can be EURUSD, eurusd, ...
     return(100);           // this could be specified in a  external file, or something like that.   
  if(_symbol=="USDCADm" || _symbol=="USDCAD")  // Attention here: depending on the broker's symbol, it can be EURUSD, eurusd, ...
     return(100);   
  if(_symbol=="USDCHFm" || _symbol=="USDCHF")  // Attention here: depending on the broker's symbol, it can be EURUSD, eurusd, ...
     return(100);     
  //return(139); //default value provided to every other pairs.   
}


int start()
 {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
     for (int cnt = OrdersTotal();cnt >= 0; cnt--) 
        { 
           if (OrderSelect(cnt, SELECT_BY_POS) == TRUE && OrderSymbol() == Symbol()) 
              { 
                 if (OrderType() == OP_BUY && OrderMagicNumber()==MagicNumber) Buyfound=true;
              
                 if (OrderType() == OP_SELL && OrderMagicNumber()==MagicNumber)  Sellfound=true;
              }
         }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////   
        
               
     
     
     double Range = (High[1]-Low[1])/10;     
    
     double Range_ref=getRangeRef(Symbol());
     if( Range>= Range_ref*Point) {
        int digits              =  MarketInfo(Symbol(),MODE_DIGITS);         
        double buy_price        =  NormalizeDouble(High[1]         , digits);
        double sell_price       =  NormalizeDouble(Low[1]          , digits);
        double buy_take_profit  =  NormalizeDouble(High[1]+400*Point, digits);
        double sell_take_profit =  NormalizeDouble(Low[1]-400*Point, digits);
        int ticket=0;
        
        // if orderstotal is huge number, we could spare time here.
        int longOrders  = OrderCount(Symbol(),OP_BUYSTOP)+OrderCount(Symbol(),OP_BUY);
        int shortOrders = OrderCount(Symbol(),OP_SELLSTOP)+OrderCount(Symbol(),OP_SELL); 
        
        if(longOrders==0)
        if(buy_price > Ask 
          //////////////////////////////////// 
          && Buyfound==false
          ///////////////////////////////////
          )  //buy stop must be above market price
        ticket=OrderSend(Symbol(),OP_BUYSTOP,Lots, buy_price,3,0,buy_take_profit,"--",MagicNumber,TimeCurrent()+4*60*60,Green);
        if(ticket==-1)
           Print("error buystop = ", GetLastError());
          
        ticket=0;   
        if(shortOrders==0)
        if(sell_price<Bid 
           ///////////////////////////////////
           && Sellfound==false
          ///////////////////////////////////
           ) //sell stop must be below market price
        ticket = OrderSend(Symbol(),OP_SELLSTOP,Lots,sell_price,3,0,sell_take_profit,"--",MagicNumber,TimeCurrent()+4*60*60,Red);
        if(ticket==-1)
           Print("error sellstop = ", GetLastError());
     }         
     return(0);
 }

double CalcLotSize()
 {  
 if(UseMoneyManagement == true)
   {
     double SingleLot = MarketInfo(Symbol(),15)/AccountLeverage();
     double LotValue = AccountEquity()* MinRisk/100;
     if(MarketInfo(Symbol(),23) == 0.1)
       {
         double Lots = NormalizeDouble(LotValue/SingleLot,1);
         if (Lots < 0.1) Lots = 0.1;
         if (Lots > 50.0) Lots = 50;
       }
     else Lots = NormalizeDouble(LotValue/SingleLot,2);
   }
 else Lots = LotSize;
 if(Lots > 50) Lots = 50;
 return(Lots);
//+------------------------------------------------------------------+

 

You can then put flags anywhere you want.

 

Regards,

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...