Gamestudio Links
Zorro Links
Newest Posts
Data from CSV not parsed correctly
by EternallyCurious. 04/18/24 10:45
StartWeek not working as it should
by Zheka. 04/18/24 10:11
folder management functions
by VoroneTZ. 04/17/24 06:52
lookback setting performance issue
by 7th_zorro. 04/16/24 03:08
zorro 64bit command line support
by 7th_zorro. 04/15/24 09:36
Zorro FIX plugin - Experimental
by flink. 04/14/24 07:48
Zorro FIX plugin - Experimental
by flink. 04/14/24 07:46
AUM Magazine
Latest Screens
The Bible Game
A psychological thriller game
SHADOW (2014)
DEAD TASTE
Who's Online Now
1 registered members (AndrewAMD), 552 guests, and 1 spider.
Key: Admin, Global Mod, Mod
Newest Members
EternallyCurious, 11honza11, ccorrea, sakolin, rajesh7827
19046 Registered Users
Previous Thread
Next Thread
Print Thread
Rate Thread
Page 3 of 5 1 2 3 4 5
Re: My Take on A Mega Script [Re: ] #434706
12/24/13 15:25
12/24/13 15:25

L
liftoff
Unregistered
liftoff
Unregistered
L



So we pick up from where we left of yesterday. I went over the process again and I seem to have propped up the average return to 47%. The current code stands as follows.
Code:
function fridayClose(int fridayclose)
{
	//allows Friday trading up until NYSE 3pm; close trades and don't allow after this
	if(fridayclose && dow() == FRIDAY && lhour(ET) >= 15) 
		{
			exitLong("*");
			exitShort("*");
			return 1; //condition met; indicate no further trades
		}
	return 0; //condition not met; safe to take new trades
}
function hourOpen(int hourblockstart, int hourblockend)
{
	//blocks new open trades between selected hours
	//uses NYSE time, including DST
	if ( (lhour(ET) >= hourblockstart) && (lhour(ET) < hourblockend) )
		return 0; //between blocked hours, do not allow trade opens
	else
		return 1; //no conditions met, allow trades by default
}
function todayOpenCombo(var dayopencombo)
{
	//allows optimizer to specify the best combo of days for opens
	//bit position 0 = Monday
	//bit position 1 = Tuesday
	//bit position 2 = Wednesday
	//bit position 3 = Thursday
	//bit position 4 = Friday
	//bit position 5 = Sunday
	//given a combination #, the function will return whether
	//current dow() is in the combination

	int dayopencombobits = dayopencombo+.5; //truncate to rounded int
	int today = dow() - 1; //Mon is 0
	if (today == 6) today = 5; //bump Sun to 5 (no Sat, keep binary range 0-63)

	if (dayopencombobits & (1 << today)) return 1; //current dow() is in the combo
		else return 0; //current dow() not in combo, do not allow trade opens
}
function todayCloseCombo(var dayclosecombo)
{
	//allows optimizer to specify the best combo of days to close by NYSE 4pm
	//bit position 0 = Monday
	//bit position 1 = Tuesday
	//bit position 2 = Wednesday
	//bit position 3 = Thursday
	//bit position 4 = Friday
	//bit position 5 = Sunday
	//given a combination #, the function will determine if we are beyond
	//a combo close time, close all trades if necessary, and return 1
	//if no further trades allowed today

	int dayclosecombobits = dayclosecombo+.5; //truncate to rounded int
	int today = dow() - 1; //Mon is 0
	if (today == 6) today = 5; //bump Sun to 5 (no Sat, keep binary range 0-63)

	if ((dayclosecombobits & (1 << today)) && lhour(ET) >= 16) 
	{
		exitLong("*");
		exitShort("*");
		return 1; //current dow() is in the combo; indicate no further trades
	}
	else return 0; //current dow() not in combo, safe to take new trades
}
function marketOpenCombo(var marketopencombo)
{
	//allows optimizer to specify best markets to initiate trades
	//bit position 0 = New York 8am-5pm Eastern
	//bit position 1 = Sydney 5pm-2am Eastern
	//bit position 2 = Tokyo 7pm-4am Eastern
	//bit position 3 = London 3am-12pm Eastern
	//given a combination #, the function will determine if current time is within
	//a market part of the combination (returns 1 to allow trading if true)
	
	int marketcombobits = marketopencombo+.5; //truncate to rounded int
	if ( (lhour(ET) >=8) && (lhour(ET) <17) && (marketcombobits & (1 << 0)) ) return 1; //inside New York
	if ( (lhour(ET) >=17) || (lhour(ET) <2) && (marketcombobits & (1 << 1)) ) return 1; //inside Sydney
	if ( (lhour(ET) >=19) || (lhour(ET) <4) && (marketcombobits & (1 << 2)) ) return 1; //inside Tokyo
	if ( (lhour(ET) >=3) && (lhour(ET) <12) && (marketcombobits & (1 << 3)) ) return 1; //inside London
	return 0; //default - current market not in combination, don't allow trade opens
}
function checkModifiers()
{
	int reversedir = 0; //default normal trade direction (0) unless specified otherwise
	int fridayclose = 0; //enforce auto-close and no trades after NYSE 3pm Friday
	int hourblockstart = 0; //block trade opens beginning at NY hour
	int hourblockend = 0; //block trade opens ending at NY hour
	int dayopencombo = optimize(61,1,63,1); //combo of days to open; 63=every day
	int dayclosecombo = optimize(29,1,63,1); //combo of days to close after NYSE 4pm; 0=none; 63=every day
	int marketopencombo = optimize(13,1,15,1); //combo of markets to allow trade opens; 15=every market

	if ( (!fridayClose(fridayclose) //close NYSE 3pm on Friday
		|| !todayCloseCombo(dayclosecombo) ) //close NYSE 4pm on selected days
		&& todayOpenCombo(dayopencombo) //open on selected days only
		&& marketOpenCombo(marketopencombo) //open during selected markets only
		&& hourOpen(hourblockstart,hourblockend) ) //open during selected hours only
			return 1; //ok to place new trades
	else
		return 0; //no trade, restricted by a modifier	
}


function run()
{
	//Parameters
  	set(PARAMETERS);
	StartDate = 20080101;
	EndDate = 20131220;
	BarPeriod = 60; //optimize(60,60,1440,60);
		
	if(is(TESTMODE)) NumSampleCycles = 6; //oversampling on Test only, not Train
	if (Train) { RollLong = 0; RollShort = 0; } //help prevent asymmetry in parameters & profit factors
	DataSplit = 70; //70% training, 30% OOS test
	NumWFOCycles = 5;
	int maxtrades = 1;

//	require minimum 30 trades per WFO cycle or stop training
	static int LastWFOCycle = 0, LastNumTrades = 0;
	if(Train && (WFOCycle != LastWFOCycle) )
	{
		if(LastNumTrades > 0 and LastNumTrades < 30)
		{
			char tradecount[100];
			sprintf(tradecount,"Not enough trades per cycle: %d",LastNumTrades);
			quit(tradecount);
		}
		LastWFOCycle = WFOCycle;
	}
	LastNumTrades = NumWinTotal+NumLossTotal;
	
	//edge trading logic
   var  BarsPassed = optimize(820,300,1300, 10);
  
   vars Price = series(price());
   vars Trend = series(LowPass(Price,BarsPassed));

   Stop = ATR(100)* optimize(3,1,6,1,-3); 
    
   if (checkModifiers())
   {
   	if(valley(Trend))
    		reverseLong(maxtrades);
   	else if(peak(Trend))
    		reverseShort(maxtrades);
	}
   
}



So I continue with the other steps.

Step 1g: Goal: determine if equity-curve trading would be helpful
Yes WFO; Yes oversample; Yes maxtrades; Yes all param optimizing; Yes best modifier(s); Yes emode
so as dusktrader advices, I will uncomment, train and test each one of the emodes.
For this strategy, emode 1 and emode 3 produce 109%, so I went with emode 1.

Step 2a: Goal: simulate actual margin and/or reinvestment
Yes rolling WFO; Yes oversample; Yes maxtrades; Yes all param optimizing; Yes modifier(s); Yes emode; Yes reinvest

So this step involves using optf to mathematically determine how good the bot has become. With this numeric evaluation, we can be more objective in comparing it to our other strategies.

So we first set the FACTOR flag on for calculating the optf figure
Code:
set(PARAMETERS+FACTORS);



We move from single lots to lots based on an account figure from now on. Meaning our margin is determined in relation to our starting capital. We are however not compounding.
The following code section lives just above the "edge trading logic" section:
Code:
//reinvest a portion of profits
	int reinvestprofits = 0; //invoke margin setting during trade logic
	Margin = 0; //default
	var MarginLong = 0; //default
	var MarginShort = 0; //default
	if (reinvestprofits)
	{
		Capital = 1000; //simulated account balance
		var riskCapital = 900; //basis to trade with
		if (OptimalF>.001) //profitable as compared to other assets
		{
			MarginLong = OptimalFLong * riskCapital;
			MarginShort = OptimalFShort * riskCapital;
		}
	}



And then just before our trade entry commands, I place this code:
Code:
if (reinvestprofits && MarginLong>0) Margin = MarginLong; else if(is(TRADEMODE)) Lots = -1;


Code:
if (reinvestprofits && MarginShort>0) Margin = MarginShort; else if(is(TRADEMODE)) Lots = -1;



So I train the strategy with reinvestment turned to 0 and turn it to true (1) and test the strategy.


The number of trades are really low. I have no idea why but I am guessing it has something to do with my code. Hopefully as I better grasp coding I can come back to this and find what is wrong.

Step 3a: Goal: identify best assets
Yes WFO; Yes oversample; Yes maxtrades; Yes all param optimizing; Yes best modifier(s); Yes emode; No reinvest
At this point I add other assets to the strategy. I was looking to add AUDUSD and NZDUSD but NZDUSD did not have the minimum 30 trades, so I set it aside and focused on EURUSD and AUDUSD. I turned reinvestment off, trained and tested.
Code:
Walk-Forward Test: TF-e1 portfolio 2008..2013
Can't open TF-e1.fac (rt)
Read TF-e1_1.par TF-e1_2.par TF-e1_3.par TF-e1_4.par
Profit 17$  MI 0$  DD 33$  Capital 39$
Trades 156  Win 44%  Avg +1.4p  Bars 7
AR 15%  PF 1.09  SR 0.22  UI 118.0%  Error 53%



With such a huge UI and error term, I have surely done something wrong.

Step 3b
Yes WFO; Yes oversample; Yes maxtrades; Yes all param optimizing; Yes best modifier(s); Yes emode; Yes reinvest; Yes multi-asset loop

So at this point I turn on reinvestment and test.
Code:
TF-e1 compiling................
Walk-Forward Test: TF-e1 portfolio 2008..2013
Can't open TF-e1.fac (rt)
Read TF-e1_1.par TF-e1_2.par TF-e1_3.par TF-e1_4.par
Profit 17$  MI 0$  DD 33$  Capital 48$
Trades 156  Win 44%  Avg +1.4p  Bars 7
CAGR 8%  PF 1.09  SR 0.20  UI 118.0%  Error 53%



I have definitely done a lot wrong along the way with such a huge Ulcer and error.
This is the code I ended up with.

Code:
function fridayClose(int fridayclose)
{
	//allows Friday trading up until NYSE 3pm; close trades and don't allow after this
	if(fridayclose && dow() == FRIDAY && lhour(ET) >= 15) 
		{
			exitLong("*");
			exitShort("*");
			return 1; //condition met; indicate no further trades
		}
	return 0; //condition not met; safe to take new trades
}
function hourOpen(int hourblockstart, int hourblockend)
{
	//blocks new open trades between selected hours
	//uses NYSE time, including DST
	if ( (lhour(ET) >= hourblockstart) && (lhour(ET) < hourblockend) )
		return 0; //between blocked hours, do not allow trade opens
	else
		return 1; //no conditions met, allow trades by default
}
function todayOpenCombo(var dayopencombo)
{
	//allows optimizer to specify the best combo of days for opens
	//bit position 0 = Monday
	//bit position 1 = Tuesday
	//bit position 2 = Wednesday
	//bit position 3 = Thursday
	//bit position 4 = Friday
	//bit position 5 = Sunday
	//given a combination #, the function will return whether
	//current dow() is in the combination

	int dayopencombobits = dayopencombo+.5; //truncate to rounded int
	int today = dow() - 1; //Mon is 0
	if (today == 6) today = 5; //bump Sun to 5 (no Sat, keep binary range 0-63)

	if (dayopencombobits & (1 << today)) return 1; //current dow() is in the combo
		else return 0; //current dow() not in combo, do not allow trade opens
}
function todayCloseCombo(var dayclosecombo)
{
	//allows optimizer to specify the best combo of days to close by NYSE 4pm
	//bit position 0 = Monday
	//bit position 1 = Tuesday
	//bit position 2 = Wednesday
	//bit position 3 = Thursday
	//bit position 4 = Friday
	//bit position 5 = Sunday
	//given a combination #, the function will determine if we are beyond
	//a combo close time, close all trades if necessary, and return 1
	//if no further trades allowed today

	int dayclosecombobits = dayclosecombo+.5; //truncate to rounded int
	int today = dow() - 1; //Mon is 0
	if (today == 6) today = 5; //bump Sun to 5 (no Sat, keep binary range 0-63)

	if ((dayclosecombobits & (1 << today)) && lhour(ET) >= 16) 
	{
		exitLong("*");
		exitShort("*");
		return 1; //current dow() is in the combo; indicate no further trades
	}
	else return 0; //current dow() not in combo, safe to take new trades
}
function marketOpenCombo(var marketopencombo)
{
	//allows optimizer to specify best markets to initiate trades
	//bit position 0 = New York 8am-5pm Eastern
	//bit position 1 = Sydney 5pm-2am Eastern
	//bit position 2 = Tokyo 7pm-4am Eastern
	//bit position 3 = London 3am-12pm Eastern
	//given a combination #, the function will determine if current time is within
	//a market part of the combination (returns 1 to allow trading if true)
	
	int marketcombobits = marketopencombo+.5; //truncate to rounded int
	if ( (lhour(ET) >=8) && (lhour(ET) <17) && (marketcombobits & (1 << 0)) ) return 1; //inside New York
	if ( (lhour(ET) >=17) || (lhour(ET) <2) && (marketcombobits & (1 << 1)) ) return 1; //inside Sydney
	if ( (lhour(ET) >=19) || (lhour(ET) <4) && (marketcombobits & (1 << 2)) ) return 1; //inside Tokyo
	if ( (lhour(ET) >=3) && (lhour(ET) <12) && (marketcombobits & (1 << 3)) ) return 1; //inside London
	return 0; //default - current market not in combination, don't allow trade opens
}
function checkModifiers()
{
	int reversedir = 0; //default normal trade direction (0) unless specified otherwise
	int fridayclose = 0; //enforce auto-close and no trades after NYSE 3pm Friday
	int hourblockstart = 0; //block trade opens beginning at NY hour
	int hourblockend = 0; //block trade opens ending at NY hour
	int dayopencombo = optimize(61,1,63,1); //combo of days to open; 63=every day
	int dayclosecombo = optimize(29,1,63,1); //combo of days to close after NYSE 4pm; 0=none; 63=every day
	int marketopencombo = optimize(13,1,15,1); //combo of markets to allow trade opens; 15=every market

	if ( (!fridayClose(fridayclose) //close NYSE 3pm on Friday
		|| !todayCloseCombo(dayclosecombo) ) //close NYSE 4pm on selected days
		&& todayOpenCombo(dayopencombo) //open on selected days only
		&& marketOpenCombo(marketopencombo) //open during selected markets only
		&& hourOpen(hourblockstart,hourblockend) ) //open during selected hours only
			return 1; //ok to place new trades
	else
		return 0; //no trade, restricted by a modifier	
}

function checkEquity(var emode)
{
	//emode 1 = standard: sets phantom/normal mode only (via Lots)
	//emode 2 = switch hitter: always in market (Lots=1), fades direction (via dir)
	//emode 3 = reward success with weighting: increase trades based on degree of improvement
	//emode 4 = mean reversion: trade when equity curve falls (Lots=1), sit out when it rises (Lots=-1)
	vars EquityCurve = series(EquityLong+EquityShort); //includes all phantom equity
	var dir; //indicates normal trade direction (dir=1) or reverse (dir=-1)

	//narrower curves
	//var slow = 50;
	//var fast = 10;

	//wider curves
	//var slow = 100;
	//var fast = 10;

	//mega-wide curves
	var slow = 200;
	var fast = 10;

	//uber-wide curves
	//var slow = 300;
	//var fast = 10;

	//optimized curves
	//var slow = optimize(50,50,300,12);
	//var fast = 10;

	vars EquityLP = series(LowPass(EquityCurve,fast));
	var EquityLPfalling = LowPass(EquityLP,slow);
	var EquityLPrisingBigger = LowPass(EquityLP,slow*3.2);
	var EquityLPrisingBig = LowPass(EquityLP,slow*1.5);
	plot("EquityLPslow",LowPass(EquityLP,slow),1,BLUE);
	plot("EquityLPfast",LowPass(EquityLP,fast),0,GREEN);
	
	if(EquityLP[0] < EquityLPfalling && falling(EquityLP)) { //drawdown
		if (emode==1) Lots = -1; //set phantom trade mode
		if (emode==2) return 1; //fade: take signals when losing
		if (emode==3) { //reward success with weighting
			Lots = -1; //set phantom trade mode
			return 1; //allow max 1 phantom trade in drawdown
		}
		if (emode==4) Lots = 1; //mean-reversion: start trading when equity curve falls
		
	}
	else { //positive equity curve
		if (emode==1) Lots = 1; //set normal trade mode
		if (emode==2) return -1; //fade: take reverse signals when winning
		if (emode==3) { //reward success with weighting
			Lots = 1; //set normal trade mode
			if (EquityLP[0] > EquityLPrisingBigger && rising(EquityLP)) return 3; //very big rising
			else if (EquityLP[0] > EquityLPrisingBig && rising(EquityLP)) return 2; //big rising
			else return 1; //rising but not yet significantly
		}
		if (emode==4) Lots = -1; //mean-reversion: stop trading when equity curve rises
	}
}

function run()
{
	//Parameters
  	set(PARAMETERS+FACTORS);
	StartDate = 20080101;
	EndDate = 20131220;
	BarPeriod = 60; //optimize(60,60,1440,60);
	LookBack = 600;
			
	if(is(TESTMODE)) NumSampleCycles = 6; //oversampling on Test only, not Train
	if (Train) { RollLong = 0; RollShort = 0; } //help prevent asymmetry in parameters & profit factors
	DataSplit = 70; //70% training, 30% OOS test
	NumWFOCycles = 5;
	int maxtrades = 1;

//	require minimum 30 trades per WFO cycle or stop training
	static int LastWFOCycle = 0, LastNumTrades = 0;
	if(Train && (WFOCycle != LastWFOCycle) )
	{
		if(LastNumTrades > 0 and LastNumTrades < 30)
		{
			char tradecount[100];
			sprintf(tradecount,"Not enough trades per cycle: %d",LastNumTrades);
			quit(tradecount);
		}
		LastWFOCycle = WFOCycle;
	}
	LastNumTrades = NumWinTotal+NumLossTotal;
		//equity-curve trading
	checkEquity(1); //emode 1: normal/phantom trading
	//reversedir = checkEquity(2); //emode 2: switch hitter
	//maxtrades = checkEquity(3); //emode 3: reward success
	//checkEquity(4); //emode 4: mean-reversion mode
	//reinvest a portion of profits
	
	while(asset(loop("EUR/USD","AUD/USD")))
	{
	
		int reinvestprofits = 1; //invoke margin setting during trade logic
		Margin = 1; //default
		var MarginLong = 0; //default
		var MarginShort = 0; //default
		if (reinvestprofits)
		{
			Capital = 50; //simulated account balance
			var riskCapital = 40; //basis to trade with
			if (OptimalF>.001) //profitable as compared to other assets
			{
				MarginLong = OptimalFLong * riskCapital;
				MarginShort = OptimalFShort * riskCapital;
			}
		}
		
		//edge trading logic
	   var  BarsPassed = optimize(820,300,1300, 10);
	  
	   vars Price = series(price());
	   vars Trend = series(LowPass(Price,BarsPassed));
	
	   Stop = ATR(100)* optimize(3,1,6,1,-3); 
	    
	   if (checkModifiers())
	   {
	   	if(valley(Trend))
	   	{
	   		if (reinvestprofits && MarginLong>0) Margin = MarginLong; else if(is(TRADEMODE)) Lots = -1;
	   		reverseLong(maxtrades);
	   	}
	   	else if(peak(Trend))
	   	{
				if (reinvestprofits && MarginShort>0) Margin = MarginShort; else if(is(TRADEMODE)) Lots = -1;
	    		reverseShort(maxtrades);
			}
	    		
		}
   }
}



I will take the time to read up on workshop 4, 5 and 6 again. Go over dusk traders modifiers and emodes and get a better understanding of them and see if I can take counter trend code in workshop 5 through the process.
If you notice where I might have made mistakes, please point them out so I can learn from them. eek

Re: My Take on A Mega Script [Re: ] #434862
12/28/13 18:57
12/28/13 18:57

L
liftoff
Unregistered
liftoff
Unregistered
L



Took a couple of days off to read and do some digging around. Looks like if I am going to find any profitable systems, I have a lot more to learn. Thankfully I have the basics of script writing in zorro down to some level. I can now identify the error of leaving out ";" ... The main reason why my first zorro adventure ended abruptly. I want to make my way through the suggested books in the first quarter of 2014. But during this period I don't want to get rusty on the script writing end so I will try taking one free system or EA out there on the web and convert it to a zorro script and see how well it fares. Since my programming skills are not that strong now, please point out logic lapses you observe in my translations.

Re: My Take on A Mega Script [Re: ] #434864
12/28/13 19:02
12/28/13 19:02

L
liftoff
Unregistered
liftoff
Unregistered
L



So I tried converting a very simple straight forward EA this evening. Its called MACD Cross AUDD1. You can follow this link to download and EA and read the rules with the MetaEditor and see if I did everything the way it should be done.
This is the script I came up with following the rules.
Code:
function run()
{
	StartDate = 2002;
	BarPeriod = 1440;
	LookBack = 150;
	//edge trading logic
   int FastPeriod = 12;
   int SlowPeriod = 26;
	int SignalPeriod = 9;
	
	vars PriceClose = series(priceClose());
	MACD(PriceClose,FastPeriod,SlowPeriod,SignalPeriod);
	vars MainLine = series(rMACD);
	vars SignalLine = series(rMACDSignal);
	vars Hist = series(rMACDHist);
	
	Stop = 30*PIP; // simple Stop
	TakeProfit = 120*PIP;
	
	if(crossOver(SignalLine,MainLine))
			enterLong();
	else if(crossUnder(SignalLine,MainLine))
		enterShort();
}



These are the results my testing produced.
Code:
AUDUSD D1 MACD cross compiling.................
BackTest: AUDUSD D1 MACD cross AUD/USD 2002..2013
Profit -111$  MI -1$  DD 138$  Capital 76$
Trades 233  Win 20%  Avg -6.2p  Bars 2
AR -14%  PF 0.76  SR -0.49  UI 343.7%  Error 48%


Re: My Take on A Mega Script [Re: ] #434868
12/28/13 19:53
12/28/13 19:53

L
liftoff
Unregistered
liftoff
Unregistered
L



Did a little tweaking optimizing the stop and running a WFO process. The code now looks like this:
Code:
function run()
{
	set(PARAMETERS);
	StartDate = 2002;
	BarPeriod = 1440;
	LookBack = 250;
	NumWFOCycles = 10;
	
	//edge trading logic
   int FastPeriod = 12;
   int SlowPeriod = 26;
	int SignalPeriod = 9;
	
	vars PriceClose = series(priceClose());
	MACD(PriceClose,FastPeriod,SlowPeriod,SignalPeriod);
	vars MainLine = series(rMACD);
	vars SignalLine = series(rMACDSignal);
	vars Hist = series(rMACDHist);
	
	Stop = ATR(100) * optimize(1.99,1,15,0.5,0); // Adaptive stop
	
		
	if(crossOver(SignalLine,MainLine))
			reverseLong(1);
	else if(crossUnder(SignalLine,MainLine))
		reverseShort(1);
	if(ReTrain) 
	{
  		UpdateDays = -1; 
  		SelectWFO = -1; 
	}	
}


And the results are as follows.
Code:
AUDUSD D1 MACD cross run..
Profit -165$  MI -2$  DD 338$  Capital 232$
Trades 132  Win 61%  Avg -16.4p  Bars 13
AR -11%  PF 0.86  SR -0.26  UI 223.3%  Error 48%
Generate Chart - please wait... ok



My aim to go around picking simple to a little complex systems and converting them to zorro scripts. I am sure if newbies come along they will find this useful and can learn by trying to converting the strategies themselves before they look at how I went about it.

Re: My Take on A Mega Script [Re: ] #434955
12/30/13 19:46
12/30/13 19:46

L
liftoff
Unregistered
liftoff
Unregistered
L



So I crossed checked the AUDUSD daily chart EA against my script by running the EA on the MT4 strategy tester and checking against the trades my script took. Looks like my script was in order and the system is just not profitable.

Re: My Take on A Mega Script [Re: ] #434957
12/30/13 20:38
12/30/13 20:38
Joined: Aug 2013
Posts: 124
D
DMB Offline
Member
DMB  Offline
Member
D

Joined: Aug 2013
Posts: 124
It's been interesting reading your investigation. Thanks.

Re: My Take on A Mega Script [Re: DMB] #435180
01/03/14 18:03
01/03/14 18:03

L
liftoff
Unregistered
liftoff
Unregistered
L



So I just finished going through Schaum's Outline of Theory and Problems of Statistics and I it does feel like I took a couple of things from the book. A lot of examples to help solidify theory. Now I make my way to Analysis of Financial Time Series by Ruey S. Tsay. I am sure it ll take me atleast to make my way through this one. In the meantime, I continue with my project of translating ideas and mt4 robots to help improve my programming skills.
Today I will be trying to translate this mt4 robot, MACD Turbo v2.0. It was featured by Robopip and based on his tests it turned out to be profitable but he tested it over only 18 months, not long enough for me.
So the mt4 code is as follows;
Code:
//+------------------------------------------------------------------+
//|                                             MACD Turbo v2.0a.mq4 |
//|                                      for GBPUSD H1 re-coded 2013 |
//|                                                 Free EA based on |
//|                                                                  |
//|                                                  MACD Sample.mq4 |
//|                      Copyright © 2005, MetaQuotes Software Corp. |
//|                                       http://www.metaquotes.net/ |
//|                                                                  |
//|                                 MACD Sample - Turbo v1.0 to v2.0 |
//|                               by XeroFX - http://www.xerofx.com/ |
//|                                                                  |
//|                                         MACD Sample - Turbo v1.1 |
//|                                      re-coded by Tjipke de Vries |
//|                                                                  |
//| Free Sample Code. We disclaim all copyright interest. Thank you. |
//+------------------------------------------------------------------+
#property copyright "Copyleft - Free Sample Code - www.xerofx.com/free-ea.html - We disclaim all copyright interest."
extern string s1 = "== Basic Settings ==";
extern double StopLoss = 255;
extern double TakeProfit = 100;
extern double TrailingStop = 25;
extern double TrailingStep = 5;
extern string s2 = "== Trade Lots Size ==";
extern double Lots = 0.1;
extern string s3 = "== Signal Logic ==";
extern double MACDOpenLevel = 3;
extern double MACDCloseLevel = 2;
extern double MATrendPeriod = 24;
extern string s4 = "== Time Filters == ";
extern string UseTradingHours = "Time Control ( 1 = True, 0 = False )";
extern int    TimeControl = 1;
extern string TimeZone = "Adjust ServerTimeZone if Required";
extern int    ServerTimeZone = 0;
extern string TradingTimes = "HourStopGMT > HourStartGMT";
extern int    HourStartGMT = 8;
extern int    HourStopGMT = 20;
extern string DontTradeFriday = "Dont Trade After FridayFinalHourGMT";
extern bool   UseFridayFinalTradeTime = TRUE;
extern int    FridayFinalHourGMT = 6;
extern string s5 = "== Extra Settings ==";
extern int    Slippage = 3;
extern double MaxSpread = 4.0;
extern int    MagicNumber = 10042;
extern string TradeComment = "MACD Turbo v2.0a";
int checkorder=1;
int SlipPage;
double Points,SL,TP;
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
// 4 or 5 Digit Broker Account Recognition
void HandleDigits()
{
    // Automatically Adjusts to Full-Pip and Sub-Pip Accounts
   if (Digits == 4 || Digits == 2)
     {
       SlipPage = Slippage;
       Points = Point;
     }
  
   if (Digits == 5 || Digits == 3)
     {
       SlipPage = Slippage*10;
       Points = Point*10;
     }
}
//----------------------- PRINT COMMENT FUNCTION
void subPrintDetails()
{
   string sComment   = "";
   string SP         = " ----------------------------------------\n";
   string NL         = "\n";
   string SessionActive,CurrentSpread,spread;
   
   TradeSession();
   MaxSpreadFilter();
   if(Digits == 4 || Digits == 5){spread = DoubleToStr(10000.0 * (Ask - Bid),1);}
   if(Digits == 2 || Digits == 3){spread = DoubleToStr(100.0 * (Ask - Bid),1);}
   if (TradeSession())SessionActive = "Trading...";
     else SessionActive = "Non-Trading Time";
   if (MaxSpreadFilter())CurrentSpread = " is to High";
     else CurrentSpread = " is OK";
   sComment = "MACD Turbo v2.0a" + NL;
   sComment = sComment + NL;
   sComment = sComment + "Magic Number " + DoubleToStr(MagicNumber,0) + NL;
   sComment = sComment + "StopLoss " + DoubleToStr(StopLoss,0) + " | ";
   sComment = sComment + "TakeProfit " + DoubleToStr(TakeProfit,0) + " | ";
   sComment = sComment + "TrailingStop " + DoubleToStr(TrailingStop,0) + NL;
   sComment = sComment + "Date: " + Month() +"-"+Day()+"-"+Year()+" Server Time: " + TimeToStr(TimeCurrent(), TIME_SECONDS) + NL;
   sComment = sComment + "GMT Time: " + TimeToStr((TimeCurrent()+ (( 0 - ServerTimeZone) * 3600)), TIME_SECONDS) + NL;
   sComment = sComment + "ServerTimeZone: " + ServerTimeZone + " (TimeZone)" + NL;
   sComment = sComment + SP;
   sComment = sComment + "Lot Size " + DoubleToStr(Lots,2) + NL;
   sComment = sComment + SessionActive + NL;
   sComment = sComment + "Spread: " + spread + CurrentSpread + NL;
   Comment(sComment);
}
//+------------------------------------------------------------------+
bool TradeSession() {
   int HourStartTrade;
   int HourStopTrade;
   HourStartTrade = HourStartGMT + ServerTimeZone;
   HourStopTrade = HourStopGMT + ServerTimeZone;
   if (HourStartTrade < 0)HourStartTrade = HourStartTrade + 24;
   if (HourStartTrade >= 24)HourStartTrade = HourStartTrade - 24;
   if (HourStopTrade > 24)HourStopTrade = HourStopTrade - 24;
   if (HourStopTrade <= 0)HourStopTrade = HourStopTrade + 24;
   if ((UseFridayFinalTradeTime && (Hour()>=FridayFinalHourGMT + ServerTimeZone) && DayOfWeek()==5)||DayOfWeek()==0)return (FALSE); // Friday Control
   if((TimeControl(HourStartTrade,HourStopTrade)!=1 && TimeControl==1 && HourStartTrade<HourStopTrade)
        || (TimeControl(HourStopTrade,HourStartTrade)!=0 && TimeControl==1 && HourStartTrade>HourStopTrade)
          ||TimeControl==0)return (TRUE); // "Trading Time";
    return (FALSE); // "Non-Trading Time";
}
//+------------------------------------------------------------------+
int TimeControl(int StartHour, int EndHour)
{
   if (Hour()>=StartHour && Hour()< EndHour)
      {
      return(0);
      }
return(1);
}
//+------------------------------------------------------------------+
bool MaxSpreadFilter()
  {
   RefreshRates();
     if ((Digits == 4 || Digits == 5)&&(10000.0 * (Ask - Bid) > MaxSpread))
       {return(true);}
     if ((Digits == 2 || Digits == 3)&&(100.0 * (Ask - Bid) > MaxSpread))
       {return(true);}
   else return(false);
  }
  
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int start()
{
   double MacdCurrent, MacdPrevious, SignalCurrent;
   double SignalPrevious, MaCurrent, MaPrevious;
   int cnt, ticket, total;
// initial data checks
// it is important to make sure that the expert works with a normal
// chart and the user did not make any mistakes setting external
// variables (Lots, StopLoss, TakeProfit,
// TrailingStop) in our case, we check TakeProfit
// on a chart of less than 100 bars
   if(Bars<100)
     {
      Print("bars less than 100");
      return(0);  
     }
   if(TakeProfit<10)
     {
      Print("TakeProfit less than 10");
      return(0);  // check TakeProfit
     }
// to simplify the coding and speed up access
// data are put into internal variables
   MacdCurrent=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,0);
   MacdPrevious=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,1);
   SignalCurrent=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,0);
   SignalPrevious=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,1);
   MaCurrent=iMA(NULL,0,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,0);
   MaPrevious=iMA(NULL,0,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,1);
   HandleDigits();
   subPrintDetails();
   total=OrdersTotal();
   
   if(checkorder<1)
     {
      // if no opened orders identified
      if(AccountFreeMargin()<(1000*Lots))
        {
         Print("You dont have enough money. Free Margin = ", AccountFreeMargin());
         return(0);
        }
      // check for long position (BUY) possibility
      if(!MaxSpreadFilter() && MacdCurrent<0 && MacdCurrent>SignalCurrent && MacdPrevious<SignalPrevious &&
         MathAbs(MacdCurrent)>(MACDOpenLevel*Points) && MaCurrent>MaPrevious && TradeSession())
        {
         ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,SlipPage,0,0,TradeComment,MagicNumber,0,Green);
         if(ticket>0)
           {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
               {
                Print("BUY order opened : ",OrderOpenPrice());
                checkorder=checkorder+1;
               }
           }
         else Print("Error opening BUY order : ",GetLastError());
         return(0);
        }
      // check for short position (SELL) possibility
      if(!MaxSpreadFilter() && MacdCurrent>0 && MacdCurrent<SignalCurrent && MacdPrevious>SignalPrevious &&
         MacdCurrent>(MACDOpenLevel*Points) && MaCurrent<MaPrevious && TradeSession())
        {
         ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,SlipPage,0,0,TradeComment,MagicNumber,0,Red);
         if(ticket>0)
           {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
               {
                Print("SELL order opened : ",OrderOpenPrice());
                checkorder=checkorder+1;
               }
           }
         else Print("Error opening SELL order : ",GetLastError());
         return(0);
        }
      return(0);
     }
   // it is important to enter the market correctly, 
   // but it is more important to exit it correctly...
if(checkorder>0)
  {
   checkorder=0;
   for(cnt=0;cnt<total;cnt++)
     {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if(OrderSymbol()==Symbol()&& // check for symbol
         OrderMagicNumber()==MagicNumber) // check the Magic Number
        {
         if(OrderType()==OP_BUY) // go to long position
           {
            checkorder=checkorder+1;
            // check for trailing stop
            if(TrailingStop>0)
              {
               if(Bid-OrderOpenPrice()>Points*TrailingStop)
                 {
                  if(OrderStopLoss()<Bid-Points*(TrailingStop+TrailingStep))
                    {
                     OrderModify(OrderTicket(),OrderOpenPrice(),Bid-Points*TrailingStop,OrderTakeProfit(),0,Green);
                     return(0);
                    }
                 }
              }
            // modify OrderStopLoss and OrderTakeProfit for Buy
            if(OrderStopLoss()==0 && OrderTakeProfit()==0 && (StopLoss>0||TakeProfit>0))
              {
               SL = OrderStopLoss();
               if (StopLoss>0) {SL =(OrderOpenPrice() - (StopLoss*Points));}
               TP = OrderTakeProfit();
               if (TakeProfit>0) {TP =(OrderOpenPrice() + (TakeProfit*Points));}
               OrderModify(OrderTicket(),OrderOpenPrice(),SL,TP,0,Green);
               return(0);
              }
           }
         if(OrderType()==OP_SELL) // go to short position
           {
            checkorder=checkorder+1;
            // check for trailing stop
            if(TrailingStop>0)
              {
               if((OrderOpenPrice()-Ask)>(Points*TrailingStop))
                 {
                  if((OrderStopLoss()>(Ask+Points*(TrailingStop+TrailingStep))) || (OrderStopLoss()==0))
                    {
                     OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Points*TrailingStop,OrderTakeProfit(),0,Red);
                     return(0);
                    }
                 }
              }
            // modify OrderStopLoss and OrderTakeProfit for Sell
            if(OrderStopLoss()==0 && OrderTakeProfit()==0 && (StopLoss>0||TakeProfit>0))
              {
               SL = OrderStopLoss();
               if (StopLoss>0) {SL =(OrderOpenPrice() + (StopLoss*Points));}
               TP = OrderTakeProfit();
               if (TakeProfit>0) {TP =(OrderOpenPrice() - (TakeProfit*Points));}
               OrderModify(OrderTicket(),OrderOpenPrice(),SL,TP,0,Red);
               return(0);
              }
           }
        }
     }
   }
   return(0);
  }
// the end.


Lets see if I can finish today but if anyone else manages to translate it before me, you are welcome to post the code so I can compare it to my final translation.

Re: My Take on A Mega Script [Re: ] #435189
01/03/14 19:31
01/03/14 19:31

L
liftoff
Unregistered
liftoff
Unregistered
L



So I did a little reading and copy and pasting gets me what I think is the zorro version of this mt4 strategy. Based on my understanding and testing it turned out to be unprofitable based on the raw code and parameters.

Code:
function hourOpen(int hourblockstart, int hourblockend)
{
	//blocks new trades between selected hours
	//uses NYSE time, including DST
	if ( (lhour(ET) >= hourblockstart) && (lhour(ET) < hourblockend) )
		return 0; //between blocked hours, do not allow trade opens
	else
		return 1; //no conditions met, allow trades by default
}

function fridayCloseTrading(int fridayfinalhourET)
{
	//blocks new open trades on fridays from the hour set
	// uses NYSE time, including DST
	if (ldow(ET) == FRIDAY && (lhour(ET)>= fridayfinalhourET))
		return 0; // during the no new trade friday period. 
	else 
		return 1; // no condition met, allow new trades by default
}

function run()
{
	StartDate = 2002;
	EndDate = 20131231;
	BarPeriod = 60;
	LookBack = 250;
	
	//edge trading logic
   int FastPeriod = 12;
   int SlowPeriod = 26;
	int SignalPeriod = 9;
	int MACDOpenLevel = 3;
	int MACDCloseLevel= 2;
	int MATrendPeriod=24;
	int OpenOrders = 2;
	int hourblockend = 3;
	int hourblockstart = 14;
	int fridayfinalhourET = 1;
	
		
	vars PriceClose = series(priceClose());
	MACD(PriceClose,FastPeriod,SlowPeriod,SignalPeriod);
	vars MainLine = series(rMACD);
	vars SignalLine = series(rMACDSignal);
	vars MA1 = series(EMA(PriceClose,MATrendPeriod));
	
	Stop = 255*PIP; // ATR(200)*5;
	Trail = 25*PIP; // ATR(200)*5;
	TakeProfit = 100*PIP;
	
	if(hourOpen(hourblockend,hourblockstart) && fridayCloseTrading(fridayfinalhourET)){
	
		if(NumOpenTotal<OpenOrders && MainLine[0]<0 && crossOver(MainLine,SignalLine) && (-1*MainLine[0])>(0.0001*MACDOpenLevel) && rising(MA1))
				reverseLong(1);
		else if(NumOpenTotal<OpenOrders && MainLine[0]>0 && crossUnder(MainLine,SignalLine) && MainLine[0]>(0.0001*MACDOpenLevel) && falling(MA1))
				reverseShort(1);
	}
//          plot("MainLine", MainLine[0], NEW, BLUE);
//				plot("SignalLine", SignalLine[0], 0, RED);
//				plot("TrendLine", MA1[0], NEW, BLACK);
}



I will go through changing some parameters tomorrow and see how it fares.

Re: My Take on A Mega Script [Re: ] #435232
01/04/14 10:12
01/04/14 10:12

L
liftoff
Unregistered
liftoff
Unregistered
L



So I just changed the stops to more adaptive stops and took out the trailing stop. Set the parameter flag and trained. It now seems to be more profitable as it has been "curve fitted". This is the code I ended up with, the original EA was built for GBPUSD. It is one of the few trend following systems I have seen that might have pulled a profit in 2013. I think it has potential and I will comeback to taking it through the evaluation process once I am done with all the recommended books.
Code:
function hourOpen(int hourblockstart, int hourblockend)
{
	//blocks new trades between selected hours
	//uses NYSE time, including DST
	if ( (lhour(ET) >= hourblockstart) && (lhour(ET) < hourblockend) )
		return 0; //between blocked hours, do not allow trade opens
	else
		return 1; //no conditions met, allow trades by default
}

function fridayCloseTrading(int fridayfinalhourET)
{
	//blocks new open trades on fridays from the hour set
	// uses NYSE time, including DST
	if (ldow(ET) == FRIDAY && (lhour(ET)>= fridayfinalhourET))
		return 0; // during the no new trade friday period. 
	else 
		return 1; // no condition met, allow new trades by default
}

function run()
{
	set(PARAMETERS);
	StartDate = 2011;
	EndDate = 2013;
	BarPeriod = 60;
	LookBack = 250;
	
	//edge trading logic
   int FastPeriod = 12;
   int SlowPeriod = 26;
	int SignalPeriod = 9;
	int MACDOpenLevel = 3;
	int MACDCloseLevel= 2;
	int MATrendPeriod=24;
	int OpenOrders = 2;
	int hourblockend = 3;
	int hourblockstart = 14;
	int fridayfinalhourET = 1;
	
		
	vars PriceClose = series(priceClose());
	MACD(PriceClose,FastPeriod,SlowPeriod,SignalPeriod);
	vars MainLine = series(rMACD);
	vars SignalLine = series(rMACDSignal);
	vars MA1 = series(EMA(PriceClose,MATrendPeriod));
	
	Stop = ATR(200)*optimize(3,1,10,1); //Adaptive Stop
	Trail = ATR(200)*optimize(5,1,10,1); //Adaptive Trail
//	TakeProfit = 100*PIP;
	
	if(hourOpen(hourblockend,hourblockstart) && fridayCloseTrading(fridayfinalhourET)){
	
		if(NumOpenTotal<OpenOrders && MainLine[0]<0 && crossOver(MainLine,SignalLine) && (-1*MainLine[0])>(0.0001*MACDOpenLevel) && rising(MA1))
				reverseLong(1);
		else if(NumOpenTotal<OpenOrders && MainLine[0]>0 && crossUnder(MainLine,SignalLine) && MainLine[0]>(0.0001*MACDOpenLevel) && falling(MA1))
				reverseShort(1);
	}
//          plot("MainLine", MainLine[0], NEW, BLUE);
//				plot("SignalLine", SignalLine[0], 0, RED);
//				plot("TrendLine", MA1[0], NEW, BLACK);
}



Code:
MACD SAMPLE compiling................
BackTest: MACD SAMPLE GBP/USD 2002..2013
Profit 199$  MI 1$  DD 202$  Capital 108$
Trades 238  Win 35%  Avg +11.0p  Bars 70
AR 16%  PF 1.20  SR 0.27  UI 51.9%  Error 40%


Everyone is welcome to use it as they wish. We are in this together.
Here is the 2002-2013 growth curve.

This is the 2011-2013 growth curve.

Re: My Take on A Mega Script [Re: ] #435239
01/04/14 14:17
01/04/14 14:17

L
liftoff
Unregistered
liftoff
Unregistered
L



A lot of free time on my hands today so I might as well try out some simple strategy translations. I will be looking at PZ Reversal Trend Following EA.

System Description:
Quote:

Trend following systems can vary, but principle elements remain the same. A reversal system, a very common system, has two modes: you are either long or short. It is always in the market and closes one position by opening a new one in the opposite direction.

With this MT4 Expert Advisor, you can either be long or short at any given time. You enter a long position and exit a short position if the current price closes above the highest price in the previous 100 days. You enter a short position and exit a long position if the current price drops below the lowest price in the previous 100 days.

This system should be applied to a huge variety of instruments to make sure to catch some big trends to pay for the other little losses. You should trade forex, commodities, indexes, interest rates, government bonds and even sectorial stocks. As a sidenote, Bill Dunn is a long term reversal trend follower that exploited the Japanese Yen to extreme levels in 1995 with a reversal system exactly like this one and has reaped incredible profits since then.


The MT4 code read as follows.
Code:
//+------------------------------------------------------------------+
//| PZ_ReversalTrendFollowingEA.mq4
//| --
//| You can either be long or short at any given time. You buy if the market 
//| makes a new 100-day high and sell if the market makes a new 100-day low. 
//| You are always in the market and break-even all trades as soon as possible.
//+------------------------------------------------------------------+
#property copyright "Copyright © http://www.pointzero-trading.com"
#property link      "http://www.pointzero-trading.com"
 
//---- Dependencies
#import "stdlib.ex4"
   string ErrorDescription(int e);
#import
 
//---- Constants
#define  ShortName         "PZ Reversal Trend Following EA"
#define  Shift             1
 
//---- External variables
extern string TR_Ex                    = "------- Trade period";
extern int    TradingPeriod            = 100;
extern string MM_Ex                    = "------- Money management";
extern bool   MoneyManagement          = true;
extern double RiskPercent              = 2;
extern double LotSize                  = 0.1;
extern string EA_Ex                    = "------- EA Settings";
extern int    Slippage                 = 6;
extern int    MagicNumber              = 2000;
 
//---- Internal
double   DecimalPip;
double   PBuy = EMPTY_VALUE;
double   PSell = EMPTY_VALUE;
 
//+------------------------------------------------------------------+
//| Custom EA initialization function
//+------------------------------------------------------------------+
int init()
{
   DecimalPip = GetDecimalPip();
   Comment("Copyright © http://www.pointzero-trading.com");
   return(0);
}
 
//+------------------------------------------------------------------+
//| Custom EA deinit function
//+------------------------------------------------------------------+
int deinit()
{
   return(0);
}
 
//+------------------------------------------------------------------+
//| Custom EA start function
//+------------------------------------------------------------------+
int start()
{   
   //--
   //-- Trade if trigger price is breached
   //--
   
   // Buy
   if(PBuy != EMPTY_VALUE && Bid > PBuy)
   { 
      PlaceOrder(OP_BUY, GetLotSize()); 
      PBuy = EMPTY_VALUE;
   }
   
   // Sell
   if(PSell != EMPTY_VALUE && Ask < PSell) 
   { 
      PlaceOrder(OP_SELL, GetLotSize()); 
      PSell = EMPTY_VALUE; 
   }
   
   //--
   //-- Check entry
   //--
   
   // Do not continue unless the bar is closed
   if(!IsBarClosed(0, true)) return(0);
   
   // Trading thresholds
   double rhigh  = iHigh(Symbol(), Period(), iHighest(Symbol(), Period(), MODE_HIGH, TradingPeriod, Shift+1));
   double rlow   = iLow(Symbol(), Period(), iLowest(Symbol(), Period(), MODE_LOW, TradingPeriod, Shift+1));
                        
   // Trades opened
   int l_TotalTrades_buy = GetTotalTrades(OP_BUY, MagicNumber);
   int l_TotalTrades_sell = GetTotalTrades(OP_SELL, MagicNumber);
  
   // Bars
   double CLOSE = iClose(Symbol(),0, Shift);
   double HIGH = iHigh(Symbol(),0, Shift);
   double LOW = iLow(Symbol(),0, Shift);
   
   // Check if buy conditions apply
   if(CLOSE > rhigh && l_TotalTrades_buy == 0)
   {
      // Buy
      PBuy = HIGH;
      CloseOrder(OP_SELL);
   }
   
   // Check if sell conditions apply
   if(CLOSE < rlow && l_TotalTrades_sell == 0)
   {
      // Sell
      PSell = LOW;
      CloseOrder(OP_BUY);
   }
   
   return (0);
}
 
//+------------------------------------------------------------------+
//| My functions
//+------------------------------------------------------------------+
 
/**
* Returns total opened trades
* @param    int   Type
* @param    int   Magic
* @return   int
*/
int GetTotalTrades(int Type, int Magic)
{
   int counter = 0;
   for (int i = OrdersTotal() - 1; i >= 0; i--)
   {
      if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
      {
        Print(ShortName +" (OrderSelect Error) "+ ErrorDescription(GetLastError()));
      } else if(OrderSymbol() == Symbol() && (OrderType() == Type || Type == EMPTY_VALUE) && OrderMagicNumber() == Magic) {
            counter++;
      }
   }
   return(counter);
}
 
/**
* Places an order
* @param    int      Type
* @param    double   Lotz
* @param    double   PendingPrice
*/
void PlaceOrder(int Type, double Lotz, double PendingPrice = 0)
{
   int err;
   color  l_color;
   double l_price, l_sprice = 0;
   RefreshRates();
   
   // Price and color for the trade type
   if(Type == OP_BUY){ l_price = Ask;  l_color = Blue; }
   if(Type == OP_SELL){ l_price = Bid; l_color = Red; } 
   
   // Avoid collusions
   while (IsTradeContextBusy()) Sleep(1000);
   int l_datetime = TimeCurrent();
   
   // Send order
   int l_ticket = OrderSend(Symbol(), Type, Lotz, l_price, Slippage, 0, 0, "", MagicNumber, 0, l_color);
   
   // Rety if failure
   if (l_ticket == -1)
   {
      while(l_ticket == -1 && TimeCurrent() - l_datetime < 60 && !IsTesting())
      {
         err = GetLastError();
         if (err == 148) return;
         Sleep(1000);
         while (IsTradeContextBusy()) Sleep(1000);
         RefreshRates();
         l_ticket = OrderSend(Symbol(), Type, Lotz, l_price, Slippage, 0, 0, "", MagicNumber, 0, l_color);
      }
      if (l_ticket == -1)
         Print(ShortName +" (OrderSend Error) "+ ErrorDescription(GetLastError()));
   }
}
 
/**
* Closes desired orders 
* @param    int   Type
*/
void CloseOrder(int Type)
{
   int l_type;
    for(int i = OrdersTotal()-1; i >= 0; i--)
    {
        OrderSelect(i, SELECT_BY_POS, MODE_TRADES); l_type = OrderType();
        if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber && Type == l_type)
        { 
          if(Type == OP_BUY || Type == OP_SELL)  
          {
            if(!OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), Slippage, Gold))
               Print(ShortName +" (OrderClose Error) "+ ErrorDescription(GetLastError()));
         } else {
            if(!OrderDelete(OrderTicket()))
               Print(ShortName +" (OrderDelete Error) "+ ErrorDescription(GetLastError()));
         }
      }
   }
}
 
/**
* Calculates lot size according to risk and the weight of this trade
* @return   double
*/
double GetLotSize()
{
   // Lots
   double l_lotz = LotSize;
   
   // Lotsize and restrictions 
   double l_minlot = MarketInfo(Symbol(), MODE_MINLOT);
   double l_maxlot = MarketInfo(Symbol(), MODE_MAXLOT);
   double l_lotstep = MarketInfo(Symbol(), MODE_LOTSTEP);
   int vp = 0; if(l_lotstep == 0.01) vp = 2; else vp = 1;
   
   // Apply money management
   if(MoneyManagement == true)
      l_lotz = MathFloor(AccountBalance() * RiskPercent / 100.0) / 1000.0;
  
   // Normalize to lotstep
   l_lotz = NormalizeDouble(l_lotz, vp);
   
   // Check max/minlot here
   if (l_lotz < l_minlot) l_lotz = l_minlot;
   if(l_lotz > l_maxlot) l_lotz = l_maxlot; 
   
   // Bye!
   return (l_lotz);
}
 
/**
* Returns decimal pip value
* @return   double
*/
double GetDecimalPip()
{
   switch(Digits)
   {
      case 5: return(0.0001);
      case 4: return(0.0001);
      case 3: return(0.001);
      default: return(0.01);
   }
}
 
/**
* Checks if the bar has closed
*/
bool IsBarClosed(int timeframe,bool reset)
{
    static datetime lastbartime;
    if(timeframe==-1)
    {
        if(reset)
            lastbartime=0;
        else
            lastbartime=iTime(NULL,timeframe,0);
        return(true);
    }
    if(iTime(NULL,timeframe,0)==lastbartime) // wait for new bar
        return(false);
    if(reset)
        lastbartime=iTime(NULL,timeframe,0);
    return(true);
}


So I crawl back into my cave to see how well I can read and translate this code.

Page 3 of 5 1 2 3 4 5

Moderated by  Petra 

Gamestudio download | chip programmers | Zorro platform | shop | Data Protection Policy

oP group Germany GmbH | Birkenstr. 25-27 | 63549 Ronneburg / Germany | info (at) opgroup.de

Powered by UBB.threads™ PHP Forum Software 7.7.1