Trade FOREX with FXCM

  • Award-Winning Platform
  • 24/7 Customer Support
  • Trade Directly on Charts
  • Free $50K Practice Account
Register


Results 91 to 105 of 127
Page 7 of 9 FirstFirst ... 3 4 5 6 7 8 9 LastLast

Thread: Single-line comment or end-of-line expected

  1. #91
    Ziklag is offline Member
    Join Date
    Nov 2008
    Posts
    85
    One step at a time; may I please have the code/snippet for (1). a trailing_Stop, and (2). how to stop the trailing at breakeven, thanks.

    I tried to search the forum ... surely I cannot be the only one in need of a trailing_stop code/snippet; but the search (results) page returns thread names, not pages and in as far as these threads have page numbers in 20s, 50s, 100s its like searching for a pin in a haystack

    I wish we could have a glossary of code/snippets for some of these basic "building block" objects ... anyway, assist me with (1). the trailing_stop code/snippet and (2) how to stop the trailing at breakeven, thanks.
    Last edited by Ziklag; 09-14-2011 at 01:07 AM.

  2. #92
    Carl A is offline FXCM Automated Platform Specialist
    Join Date
    Oct 2010
    Posts
    797
    Hi Ziklag,

    Thanks for posting.

    Please see check out this thread for the trailing stop snippet: http://forexforums.dailyfx.com/codin...tml#post912610 (Trailing stop code snippet)

    Best Regards,
    Carl

  3. #93
    Ziklag is offline Member
    Join Date
    Nov 2008
    Posts
    85
    Hi,

    Help me with code/snippet for a movavgcross2line stEA.

    regards

  4. #94
    jpschan is offline FXCM Automated Platform Specialist
    Join Date
    Dec 2010
    Posts
    1,061
    Quote Originally Posted by Ziklag View Post
    Hi,

    Help me with code/snippet for a movavgcross2line stEA.

    regards
    Here is a smovavgcross2line stEA, except it has a time filter.

    http://forexforums.dailyfx.com/free-...me-filter.html (EMA 2 Line Cross with Time Filter)

    Regards,
    jpschan

  5. #95
    Ziklag is offline Member
    Join Date
    Nov 2008
    Posts
    85
    Much appreciated jpschan,

    How do I edit it to remove 'Time Filter' and its 'Dollar value Stops and Limits.'

    regards.



    using System;
    using Broker.StrategyLanguage.Function;
    namespace Broker.StrategyLanguage.Strategy
    {
    public class EMA2LineWithTimeFilter : BaseStrategyAdvisor
    {
    private ISeries<Double> m_price;
    private int m_fastlength = 9;
    private int m_slowlength = 18;
    private XAverage m_average1;
    private XAverage m_average2;
    private SeriesVar<Double> m_fastavg;
    private SeriesVar<Double> m_slowavg;
    private int m_OpeningHour = 3;
    private int m_ClosingHour = 11;
    private double m_Stop_Amount = 80;
    private double m_Profit_Target_Amount = 145;
    private bool checktime;
    private double m_shareorposition = 1;
    private IMarketOrder m_Order0;
    private IMarketOrder m_Order1;
    private IMarketOrder m_Order2;
    private IMarketOrder m_Order3;
    public EMA2LineWithTimeFilter(object ctx) :
    base(ctx) {}

    public double shareorposition{
    get { return m_shareorposition; }
    set { m_shareorposition = value; }
    }
    private ISeries<Double> price{
    get { return m_price; }
    }

    [Input]
    public int fastlength{
    get { return m_fastlength; }
    set { m_fastlength = value; }
    }
    [Input]
    public int slowlength{
    get { return m_slowlength; }
    set { m_slowlength = value; }
    }
    [Input]
    public int OpeningHour{
    get { return m_OpeningHour; }
    set { m_OpeningHour = value; }
    }
    [Input]
    public int ClosingHour{
    get { return m_ClosingHour; }
    set { m_ClosingHour = value; }
    }
    [Input]
    public double Stop_Amount{
    get { return m_Stop_Amount; }
    set { m_Stop_Amount = value; }
    }

    [Input]
    public double Profit_Target_Amount{
    get { return m_Profit_Target_Amount; }
    set { m_Profit_Target_Amount = value; }
    }
    protected override void Construct(){
    m_average1 = new XAverage(this);
    m_average2 = new XAverage(this);
    m_fastavg = new SeriesVar<Double>(this);
    m_slowavg = new SeriesVar<Double>(this);
    m_Order0 =
    OrdersFactory.CreateMarketNextBar(new OrdersCreateParams(Lots.Default, "EMATFCrossLong", OrderAction.Buy));
    m_Order1 =
    OrdersFactory.CreateMarketNextBar(new OrdersCreateParams(Lots.Default, "EMATFCrossShort",
    OrderAction.SellShort));
    m_Order2 =
    OrdersFactory.CreateMarketNextBar(new OrdersCreateParams(Lots.Default, "L-C", OrderAction.Sell));
    m_Order3 =
    OrdersFactory.CreateMarketNextBar(new OrdersCreateParams(Lots.Default, "S-C", OrderAction.BuyToCover));

    }
    protected override void Initialize(){
    m_price = Bars.Close;
    m_average1.price = price;
    m_average1.length = new Serie---pression<Int32>(delegate { return fastlength; });
    m_average2.price = price;
    m_average2.length = new Serie---pression<Int32>(delegate { return slowlength; });
    m_fastavg.DefaultValue = 0;
    m_slowavg.DefaultValue = 0;
    }
    protected override void Destroy() {}
    protected override void Execute(){

    if ((Bars.TimeValue.Hour > OpeningHour) && (Bars.TimeValue.Hour < ClosingHour)){
    checktime = true;
    }
    else{
    checktime = false;
    }

    m_fastavg.Value = m_average1[0];
    m_slowavg.Value = m_average2[0];

    if(checktime == true){
    if ((Functions.DoubleGreater(Bars.CurrentBar, 1) && Functions.CrossesOver(this, m_fastavg, m_slowavg))){
    m_Order0.Generate();
    }
    if ((Functions.DoubleGreater(Bars.CurrentBar, 1) && Functions.CrossesUnder(this, m_fastavg, m_slowavg))){
    m_Order1.Generate();
    }}

    if(StrategyInfo.MarketPosition > 0){
    if ((Functions.DoubleGreater(Bars.CurrentBar, 1) && Functions.CrossesUnder(this, m_fastavg, m_slowavg))){
    m_Order2.Generate();
    }}
    if(StrategyInfo.MarketPosition < 0){
    if ((Functions.DoubleGreater(Bars.CurrentBar, 1) && Functions.CrossesOver(this, m_fastavg, m_slowavg))){
    m_Order3.Generate();
    }}

    if ((shareorposition == 1)){
    CurSpecOrdersMode = SpecOrdersMode.perLot;
    }
    else{
    CurSpecOrdersMode = SpecOrdersMode.perPosition;
    }
    if (Functions.DoubleGreater(Profit_Target_Amount, 0)){
    GenerateProfitTarget(Profit_Target_Amount);
    }
    if (Functions.DoubleGreater(Stop_Amount, 0)){
    GenerateStopLoss(Stop_Amount);
    }

    }
    }
    }

  6. #96
    jpschan is offline FXCM Automated Platform Specialist
    Join Date
    Dec 2010
    Posts
    1,061
    Hi Ziklag,

    I thought you already have the MovAvg2LineCross stEA. The code in red is the code for time filter and dollar value stop and limit

    Code:
    protected override void Execute(){
    
        if ((Bars.TimeValue.Hour > OpeningHour) && (Bars.TimeValue.Hour < ClosingHour)){
    		checktime = true;
    	}
    	else{
    		checktime = false;
    	}
    
       m_fastavg.Value = m_average1[0];
       m_slowavg.Value = m_average2[0];
    	
       if(checktime == true){
       		if ((Functions.DoubleGreater(Bars.CurrentBar, 1) && Functions.CrossesOver(this, m_fastavg, m_slowavg))){
           		m_Order0.Generate();
       		}
       		if ((Functions.DoubleGreater(Bars.CurrentBar, 1) && Functions.CrossesUnder(this, m_fastavg, m_slowavg))){
           		m_Order1.Generate();
       }}
    
       if(StrategyInfo.MarketPosition > 0){
    		if ((Functions.DoubleGreater(Bars.CurrentBar, 1) && Functions.CrossesUnder(this, m_fastavg, m_slowavg))){
    			m_Order2.Generate();
    		}}
       if(StrategyInfo.MarketPosition < 0){
    		if ((Functions.DoubleGreater(Bars.CurrentBar, 1) && Functions.CrossesOver(this, m_fastavg, m_slowavg))){
    			m_Order3.Generate();
    		}}
    
       if ((shareorposition == 1)){
           CurSpecOrdersMode = SpecOrdersMode.perLot;
       }
       else{
           CurSpecOrdersMode = SpecOrdersMode.perPosition;
       }
       if (Functions.DoubleGreater(Profit_Target_Amount, 0)){
           GenerateProfitTarget(Profit_Target_Amount);
       }
       if (Functions.DoubleGreater(Stop_Amount, 0)){
           GenerateStopLoss(Stop_Amount);
       }
       
    }
    Regards,
    jpschan

  7. #97
    Ziklag is offline Member
    Join Date
    Nov 2008
    Posts
    85
    Hello,

    I've raised this complaint before. See attached snapshot: a signal to short the instrument is given followed by a signal to buy; a trade (long) is entered only to be closed immediately. This happens when two opposing signals are given on adjacent bars; I use this strategy with IOG on, also note that the errant module is trailstop - it is the one that gets filled immediately it is generated in the instance of opposing signals on adjacent bars.
    As I said I've raised this complaint before so please examine the code, I just missed money today.

    Regards.
    Attached Thumbnails Attached Thumbnails Single-line comment or end-of-line expected-trail3.jpg  

    Attached Files Attached Files
    Last edited by Ziklag; 10-12-2011 at 05:05 AM.

  8. #98
    jimmylmh is offline FXCM Automated Platform Specialist
    Join Date
    Dec 2010
    Posts
    964
    Hi Ziklag,

    Thank you for your post.

    While I am not the creator of the stEA, I don't know exactly what is the flow of the trading logic or the reason behind how the code is written.

    Upon a quick look at the code, it appears that the variable pTrailPrice might be the caused of this behavior. You might want to track the change of this variable by using the Output.WriteLine method which you can print out the variable to examine how it is reacting with other conditions.

    Let us know if you have further questions.

    By the way, if you have difficulties in coding your trading strategies, you might want to use our programming service which our programmers could help you in completing the trading strategies. Please visit FXCM for more information.

    Regards,
    Jimmy

  9. #99
    Ziklag is offline Member
    Join Date
    Nov 2008
    Posts
    85
    Hello,

    The pTrailPrice code/module whose stop gets filled immediately it is generated when opposing signals appear on adjacent bars as captured in the snapshot above was provided by Carl A, see post #92.
    Would you please have that member look at the problem; perhaps could be better placed to help.

    Regards.

  10. #100
    jpschan is offline FXCM Automated Platform Specialist
    Join Date
    Dec 2010
    Posts
    1,061
    Quote Originally Posted by Ziklag View Post
    Hello,

    The pTrailPrice code/module whose stop gets filled immediately it is generated when opposing signals appear on adjacent bars as captured in the snapshot above was provided by Carl A, see post #92.
    Would you please have that member look at the problem; perhaps could be better placed to help.

    Regards.
    Hi Ziklag,

    Could you please provide the code and a detail description of the problem?

    Regards,
    jpschan

  11. #101
    Ziklag is offline Member
    Join Date
    Nov 2008
    Posts
    85
    jpschan,

    See post #97 the code is attached. The logic is straight forward; when a bar closes below the MA a short signal/order is generated with a trailing-stop, m_initialstop = 40 (IOG on). All is well until adjacent bars generate signals/orders in which case the last/second order, in the instance of post #97 the buy signal/order, has its trailstop filled immediately it is generated thereby exiting the position prematurely. Actually post #97 captures what happened on Wednesday, that move went on to create about 200pips that I missed.
    The problem apparently is, instead of m_initialstop = 40 it appears like in this instance one gets m_initialstop = market, that is what has to be investigated.

    Actually I've just discovered that it does not necessarily have to be adjacent bars but any/all instances where the previous position is held to the point where a another/new/opposing signal is generated so that the task of discarding the old and initiating the new results in the new/second/last signal/order getting m_initialstop = market instead of m_initialstop = 40

    Regards.
    Last edited by Ziklag; 10-14-2011 at 02:24 AM.

  12. #102
    jpschan is offline FXCM Automated Platform Specialist
    Join Date
    Dec 2010
    Posts
    1,061
    Hi Ziklag,

    Please re-Initialize pLastPrice and pTrailPrice inside TrailStop() method.

    Code:
    protected override void Execute()
    {
    	IFxAccount acc = Fx2GoHost.Accounts[0];
    
    	//Gets account equity depending on whether live or backtesting			
    	if (Environment.StrategyAuto)
    	{
    		accountequity = acc.Equity;
    	} 
    	else 
    	{
    		accountequity = InitialCapital + StrategyInfo.OpenEquity;	
    	}
    
    	numlots = ((int) ((accountequity / 1000.0 ) / 1.0)) * 1;  //returns a rounded down lot size based on $500 equity per lot
    
    	if (Bars.Status == BarStatus.Close)
    	{
    		m_avg = m_averagefc1[0];
    		if (Functions.DoubleGreater(price[0], m_avg))
    		{
    			m_counterl.Value = (m_counterl.Value + 1);
    		}
    		else
    		{
    			m_counterl.Value = 0;
    		}
    		if ((Functions.DoubleGreater(Bars.CurrentBar, confirmbars) && (m_counterl.Value == confirmbars)))
    		{					
    			m_Order0.Generate(numlots);
    			//pLastPrice = 0;
    			//pTrailPrice = 0;					
    		}
    		if (Functions.DoubleLess(price[0], m_avg))
    		{
    			m_counters.Value = (m_counters.Value + 1);
    		}
    		else
    		{
    			m_counters.Value = 0;
    		}
    		if ((Functions.DoubleGreater(Bars.CurrentBar, confirmbars) && (m_counters.Value == confirmbars)))
    		{
    			m_Order1.Generate(numlots);	
    			//pLastPrice = 0;
    			//pTrailPrice = 0;		
    		}
    	}
    	TrailStop();
    }
    private void TrailStop()
    {
    	if(pLastPrice == 0)
    		pLastPrice = Bars.Close[0];
    	if(StrategyInfo.MarketPosition > 0)
    	{
    
    		if(pTrailPrice == 0)
    			pTrailPrice = StrategyInfo.AvgEntryPrice - Bars.Point*10*m_initialstop;
    		
    		if(Bars.Close[0] > pLastPrice)
    		{
    			pTrailPrice += (Bars.Close[0] - pLastPrice);
    			pLastPrice = Bars.Close[0];
    		}
    		if (!setBreakevenBuy)
    			trailstop_buy_order.Generate(pTrailPrice, StrategyInfo.MarketPosition);
    	}
    	else if(StrategyInfo.MarketPosition < 0)
    	{
    
    		if(pTrailPrice == 0)
    			pTrailPrice = StrategyInfo.AvgEntryPrice + Bars.Point*10*m_initialstop;
    
    	
    		if(Bars.Close[0] < pLastPrice)
    		{
    			pTrailPrice -= (pLastPrice - Bars.Close[0]);
    			pLastPrice = Bars.Close[0];
    		}
    		if (!setBreakevenSell)
    			trailstop_sell_order.Generate(pTrailPrice, (-1)*StrategyInfo.MarketPosition);
    	}
    	else
    	{
    		pLastPrice = 0;
    		pTrailPrice = 0;
    	}
    
    
    
    	// TODO : implement indicator logic here 
    	if (StrategyInfo.MarketPosition > 0)
    	{
    		SellLimit.Generate(StrategyInfo.AvgEntryPrice + 0.0350);
    	}
    	else if (StrategyInfo.MarketPosition < 0)
    	{
    		BuyLimit.Generate(StrategyInfo.AvgEntryPrice - 0.0350);
    	}
    	
    	
    	// TODO : implement indicator logic here 
    	if (StrategyInfo.MarketPosition > 0)
    	{
    		setBreakevenSell = false;
    
    		if (Bars.High[0] > StrategyInfo.AvgEntryPrice + 0.0040)
    			setBreakevenBuy = true;
    
    		if (setBreakevenBuy)
    			breakEvenSellStop.Generate(StrategyInfo.AvgEntryPrice);
    	}
    	else if (StrategyInfo.MarketPosition < 0)
    	{
    		setBreakevenBuy = false;
    
    		if (Bars.Low[0] < StrategyInfo.AvgEntryPrice - 0.0040)
    			setBreakevenSell = true;
    
    		if (setBreakevenSell)
    			breakEvenBuyStop.Generate(StrategyInfo.AvgEntryPrice);
    	}
    	else
    	{
    		setBreakevenBuy = false;
    		setBreakevenSell = false;
    	}
    }
    Regards,
    jpschan

  13. #103
    Ziklag is offline Member
    Join Date
    Nov 2008
    Posts
    85
    Thanks jpschan but still, no joy ;-( In the code, here attached, I made the correction you suggested but on testing, as is captured in the snapshot, each of the two successful short trades shown is followed by a buy signal/trade that failed - nipped in the bud by TrailStopSell

    The task of discarding the preceding trade with its associated stop/limit orders and initiating the new still results in the new/second/last signal/order getting m_initialstop = market instead of m_initialstop = 40.

    Regards.
    Attached Thumbnails Attached Thumbnails Single-line comment or end-of-line expected-fxcm-strategy-trader2.jpg  

    Attached Files Attached Files

  14. #104
    robocod's Avatar
    robocod is offline Member
    Join Date
    Mar 2011
    Posts
    249
    I'm sorry I didn't have time to look at the whole code, or the discussion. I just looked at the last few comments.

    It seems maybe the " re-Initialize pLastPrice and pTrailPrice inside TrailStop() method" suggestion was not quite right.

    The logic of the code resets the prices if MarketPosition == 0. But this doesn't take into account the case where the MarketPosition changes from >0 to <0 in one tick, which it will do in the case that a "buy" was triggered when you were already short (it closes the short and opens the long), and vice versa of course.

    What you could try is to keep a variable of the last MarketPosition, and then reset the pLastPrice and pTrailPrice when the state changes.

    Something like this...

    PHP Code:
    // In variable definition section
    private int lastMarketPosition;

    // In Initialize()
    lastMarketPosition 0;

    // In TrailStop or wherever you put the logic
    {
       ...

        if (
    lastMarketPosition != StrategyInfo.MarketPosition)
        {
            
    pLastPrice 0;
            
    pTrailPrice 0;
            
    lastMarketPosition  StrategyInfo.MarketPosition;
        }

       ... 
    I do something similar to this in my own strategy and it seems to work fine. Of course, I didn't check the rest of your logic, etc. there could be other issues, but this might be better.

  15. #105
    jpschan is offline FXCM Automated Platform Specialist
    Join Date
    Dec 2010
    Posts
    1,061
    Hi robocod and Ziklag,

    Thank you for posting. robocod is correct. You need to keep track of the change in position from >0 to <0 and vice versa. Thanks robocod for pointing out the problem.

    Regards,
    jpschan

Page 7 of 9 FirstFirst ... 3 4 5 6 7 8 9 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Disclaimer: Trading foreign exchange on margin carries a high level of risk, and may not be suitable for all investors. The high degree of leverage can work against you as well as for you. Before deciding to trade foreign exchange you should carefully consider your investment objectives, level of experience, and risk appetite. The possibility exists that you could sustain a loss of some or all of your initial investment and therefore you should not invest money that you cannot afford to lose. You should be aware of all the risks associated with foreign exchange trading, and seek advice from an independent financial advisor if you have any doubts. Any opinions, news, research, analyses, prices, or other information contained on this website is provided as general market commentary and does not constitute investment advice. Forex Capital Markets LLC. will not accept liability for any loss or damage, including without limitation to, any loss of profit, which may arise directly or indirectly from use of or reliance on such information.