New at Programming, stuck with a crossover strat - futures io
futures io futures trading



New at Programming, stuck with a crossover strat


Discussion in NinjaTrader

Updated
      Top Posters
    1. looks_one DeadCatBounced with 7 posts (0 thanks)
    2. looks_two gregid with 3 posts (4 thanks)
    3. looks_3 Zondor with 1 posts (1 thanks)
    4. looks_4 Tasker_182 with 1 posts (1 thanks)
      Best Posters
    1. looks_one gregid with 1.3 thanks per post
    2. looks_two Zondor with 1 thanks per post
    3. looks_3 Tasker_182 with 1 thanks per post
    4. looks_4 shodson with 1 thanks per post
    1. trending_up 2,406 views
    2. thumb_up 7 thanks given
    3. group 5 followers
    1. forum 13 posts
    2. attach_file 0 attachments




Welcome to futures io: the largest futures trading community on the planet, with well over 125,000 members
  • Genuine reviews from real traders, not fake reviews from stealth vendors
  • Quality education from leading professional traders
  • We are a friendly, helpful, and positive community
  • We do not tolerate rude behavior, trolling, or vendors advertising in posts
  • We are here to help, just let us know what you need
You'll need to register in order to view the content of the threads and start contributing to our community.  It's free and simple.

-- Big Mike, Site Administrator

(If you already have an account, login at the top of the page)

 
Search this Thread
 

New at Programming, stuck with a crossover strat

(login for full post details)
  #1 (permalink)
Baltimore MD US
 
Experience: Intermediate
Platform: NinjaTrader
Trading: ES, NQ
 
DeadCatBounced's Avatar
 
Posts: 293 since Apr 2013
Thanks: 1,514 given, 724 received

Hello

Just getting into programming so I thought I would set myself a challenge of building what I thought would be a fairly simple strategy. I am attempting to create a strategy that does the following: When the price reaches a point that is + or - 5 ticks of it either goes long or short.

Example: my indicator (lets use a SMA just for example) is at 95.05 the price is currently at 94.8. What I would like to have happen is that as the price moves up, at 95.00 it will enter a short position. If the price continues to go up at 95.10 it would reverse and enter a long position. (or vice versa ofc if the price was coming down to my SMA.

I started out using the wizard, and then looking at the view code button of the different sample strategies figured I would need to use an if, then else if statement to effect the reverse.

Here is my code currently.

 
Code
#region Using declarations
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Data;
using NinjaTrader.Indicator;
using NinjaTrader.Gui.Chart;
using NinjaTrader.Strategy;
#endregion

// This namespace holds all strategies and is required. Do not change it.
namespace NinjaTrader.Strategy
{
    /// <summary>
    /// bam
    /// </summary>
    [Description("bam")]
    public class MA2 : Strategy
    {
        #region Variables
        // Wizard generated variables
        private int sMAlookback = 50; // Default setting for SMAlookback
        private int offset = 5; // Default setting for Offset
        private int offsetneg = -5; // Default setting for Offsetneg
        // User defined variables (add any user defined variables below)
        #endregion

        /// <summary>
        /// This method is used to configure the strategy and is called once before any strategy method is called.
        /// </summary>
        protected override void Initialize()
        {
            Add(SMA(SMAlookback));
            Add(SMA(SMAlookback));

            CalculateOnBarClose = false;
        }

        /// <summary>
        /// Called on each bar update event (incoming tick)
        /// </summary>
        protected override void OnBarUpdate()
        {
			Print("LongCurrentAsk: "+GetCurrentAsk()+" Offset+Tick: "+(Offset * TickSize)+" SMA: "+SMA(SMAlookback)[0]);
			Print("Calculated value: "+(GetCurrentAsk() + Offset * TickSize));
			
			Print("ShortCurrentBid: "+GetCurrentBid()+" Offsetneg+Tick: "+(Offsetneg * TickSize)+" SMA: "+SMA(SMAlookback)[0]);
			Print("Calculated value: "+(GetCurrentBid() + Offsetneg * TickSize));
			
            if (CrossAbove(GetCurrentAsk() + Offset * TickSize, SMA(SMAlookback), 1))
                EnterLong(DefaultQuantity, "");
            else if (CrossBelow(GetCurrentBid() + Offsetneg * TickSize, SMA(SMAlookback), 1))
                EnterShort(DefaultQuantity, "");
        }
		
		

        #region Properties
        [Description("")]
        [GridCategory("Parameters")]
        public int SMAlookback
        {
            get { return sMAlookback; }
            set { sMAlookback = Math.Max(50, value); }
        }

        [Description("")]
        [GridCategory("Parameters")]
        public int Offset
        {
            get { return offset; }
            set { offset = Math.Max(5, value); }
        }

        [Description("")]
        [GridCategory("Parameters")]
        public int Offsetneg
        {
            get { return offsetneg; }
            set { offsetneg = Math.Max(-5, value); }
        }
        #endregion
    }
}
Anyways, currently it does not seem anything is working. Not sure what I am doing wrong - when I hit the compile button it doesn't come up with any logic errors. If someone could help me with this that would be great!

Also, I was looking at purchasing this ebook: Smashwords ? NinjaScript Programmer's Launch Pad ? A book by Scott Daggett to assist me in learning the basics of ninjascript programming - does anyone have experience with this and if it is worth the time?

Visit my futures io Trade Journal Started this thread Reply With Quote

Journal Challenge February 2021 results (so far):
Competing for $1500 in prizes from Topstep
looks_oneSBtrader82 's Trading Journalby SBtrader82
(154 thanks from 29 posts)
looks_twoJust BEING a Trader: Letting Go!!by iqgod
(111 thanks from 32 posts)
looks_3Wisdom is Emptinessby Mtype
(68 thanks from 25 posts)
looks_4Deetee’s DAX Trading Journal (time based)by Deetee
(31 thanks from 16 posts)
looks_5Journal for peanuts1956by peanuts1956
(23 thanks from 13 posts)
 
 
(login for full post details)
  #3 (permalink)
Wrocław, Poland
 
Experience: Intermediate
Platform: NinjaTrader, Racket
Trading: Ockham's razor
 
gregid's Avatar
 
Posts: 651 since Aug 2009
Thanks: 320 given, 620 received


add brackets in correct places:
change:
 
Code
GetCurrentAsk() + Offset * TickSize
to:
 
Code
GetCurrentAsk() + (Offset * TickSize)

Also if you are new to programming always use curly brackets with conditions:
 
Code
if (condition1)
{
    something;
}
else
{
   somethingelse;
}
this will save you a lot of problems in the near future

Reply With Quote
The following 2 users say Thank You to gregid for this post:
 
(login for full post details)
  #4 (permalink)
Baltimore MD US
 
Experience: Intermediate
Platform: NinjaTrader
Trading: ES, NQ
 
DeadCatBounced's Avatar
 
Posts: 293 since Apr 2013
Thanks: 1,514 given, 724 received

Thanks for the help.

I added in the brackets so the code now looks like this:

 
Code
            if (CrossAbove(GetCurrentAsk() + (Offset * TickSize), SMA(SMAlookback), 1))
			{
                EnterShort(DefaultQuantity, "");
			}
            else if (CrossBelow(GetCurrentBid() + (Offsetneg * TickSize), SMA(SMAlookback), 1))
			{
                EnterLong(DefaultQuantity, "");
			}
It is sort of working. For whatever reason it was going long when I meant it to go short and short when I meant it to go long so I switched the short/ long orders and the directions are atleast good.

However it doesnt seem to reverse, it only does the one trade?

Visit my futures io Trade Journal Started this thread Reply With Quote
 
(login for full post details)
  #5 (permalink)
Portland Oregon, United States
 
Experience: Beginner
Platform: Ninjatrader®
Broker: CQG, Kinetick
Trading: Gameplay Klownbine® Trading of Globex
 
Zondor's Avatar
 
Posts: 1,347 since Jul 2009
Thanks: 1,245 given, 2,721 received

You are not using predefined reusable instances of the external class, which in this case is the SMA class..

Not doing so exacts a huge performance penalty.

Refer to the "Anyone have any hints for Optimizing C# code" thread for a further explanation.

The strategy wizard produces code in a simplistic manner without regard for its operational efficiency.

The examples in the Ninjatrader Help coding tutorials likewise ignore such considerations.

"If we don't loosen up some money, this sucker is going down." -GW Bush, 2008
“Lack of proof that something is true does not prove that it is not true - when you want to believe.” -Humpty Dumpty, 2014
“The greatest shortcoming of the human race is our inability to understand the exponential function.”
Prof. Albert Bartlett
Follow me on Twitter Visit my futures io Trade Journal Reply With Quote
The following user says Thank You to Zondor for this post:
 
(login for full post details)
  #6 (permalink)
Baltimore MD US
 
Experience: Intermediate
Platform: NinjaTrader
Trading: ES, NQ
 
DeadCatBounced's Avatar
 
Posts: 293 since Apr 2013
Thanks: 1,514 given, 724 received

Hey Zondor thanks for the reply.

So what I am reading in that other thread is basically the way the SMA is calculated is every tick throughout the bar it is recalculated which obviously takes up computing power.

Looking at the code for the stochastic that you optimized you put in a If statement

if(FirstTickOfBar)

Whereas in Richard Todd's article that I found on the ninjatrader link he uses

a void OnBarUpdate.

im thinking that because I do want every tick to check if it has gotten close to the SMA for my entry conditions I will use the void OnBarUpdate?

Visit my futures io Trade Journal Started this thread Reply With Quote
 
(login for full post details)
  #7 (permalink)
Baltimore MD US
 
Experience: Intermediate
Platform: NinjaTrader
Trading: ES, NQ
 
DeadCatBounced's Avatar
 
Posts: 293 since Apr 2013
Thanks: 1,514 given, 724 received

I still cannot get it to reverse positions for me.

When I looked at the code for the SampleMACrossOver strat that ninja supplies (here is their code)

 
Code
			if (CrossAbove(SMA(Fast), SMA(Slow), 1))
			    EnterLong();
			else if (CrossBelow(SMA(Fast), SMA(Slow), 1))
			    EnterShort();
It reverses fine.

Yet my code, which I think has the same basic logic:

 
Code
            if (CrossAbove(GetCurrentAsk() + (Offset * TickSize), SMA(SMAlookback), 1))
			{
                EnterShort(DefaultQuantity, "");
			}
            else if (CrossBelow(GetCurrentBid() + (Offsetneg * TickSize), SMA(SMAlookback), 1))
			{
                EnterLong(DefaultQuantity, "");
			}

Only goes has the one entry and will not reverse on me :/

Any ideas on what I am doing wrong?

Visit my futures io Trade Journal Started this thread Reply With Quote
 
(login for full post details)
  #8 (permalink)
Wrocław, Poland
 
Experience: Intermediate
Platform: NinjaTrader, Racket
Trading: Ockham's razor
 
gregid's Avatar
 
Posts: 651 since Aug 2009
Thanks: 320 given, 620 received

Try removing the empty string in your EnterLong and EnterShort:

 
Code
EnterLong(DefaultQuantity);
Give it a try as (possibly!) the string identifies the order therefore NT waits for you exiting the named order first.

Reply With Quote
The following user says Thank You to gregid for this post:
 
(login for full post details)
  #9 (permalink)
Baltimore MD US
 
Experience: Intermediate
Platform: NinjaTrader
Trading: ES, NQ
 
DeadCatBounced's Avatar
 
Posts: 293 since Apr 2013
Thanks: 1,514 given, 724 received

Thanks for the help gregid, no luck tho :/

Visit my futures io Trade Journal Started this thread Reply With Quote
 
(login for full post details)
  #10 (permalink)
Cedar Rapids, iowa
 
Experience: Intermediate
Platform: Ninjatrader
Broker: Ninjatrader - Continuum
Trading: 6E, TF, 6J
 
Tasker_182's Avatar
 
Posts: 593 since Aug 2009
Thanks: 430 given, 1,142 received



Trader Chris View Post
I still cannot get it to reverse positions for me.

When I looked at the code for the SampleMACrossOver strat that ninja supplies (here is their code)

 
Code
			if (CrossAbove(SMA(Fast), SMA(Slow), 1))
			    EnterLong();
			else if (CrossBelow(SMA(Fast), SMA(Slow), 1))
			    EnterShort();
It reverses fine.

Yet my code, which I think has the same basic logic:

 
Code
            if (CrossAbove(GetCurrentAsk() + (Offset * TickSize), SMA(SMAlookback), 1))
			{
                EnterShort(DefaultQuantity, "");
			}
            else if (CrossBelow(GetCurrentBid() + (Offsetneg * TickSize), SMA(SMAlookback), 1))
			{
                EnterLong(DefaultQuantity, "");
			}

Only goes has the one entry and will not reverse on me :/

Any ideas on what I am doing wrong?


If you haven't already done so, read the NinjaTrader help file and in particular look for the statements you are using and what their requirements are. It takes time to go through the help file but there really is quite a bit of relevant info and examples in there.

In general:
1) When something does not seem to execute check the Ninja Log for any error statements. Also bring up the output window to see if anything is printed there.
2)use Print statements (that output to the Output window) to identify that your code is executing through the logical area in question. For example use a Print statement in your "else if" section to show that the program is going through the "else if" section. If it does then use further print statements perhaps to advise the status of the variables being used to help understand the logic decisions.

It can be frustrating yet rewarding when you make breakthroughs in coding, just keep plugging away.

Reply With Quote
The following user says Thank You to Tasker_182 for this post:
 
(login for full post details)
  #11 (permalink)
Baltimore MD US
 
Experience: Intermediate
Platform: NinjaTrader
Trading: ES, NQ
 
DeadCatBounced's Avatar
 
Posts: 293 since Apr 2013
Thanks: 1,514 given, 724 received

Thanks for your reply Tasker_182!

Yeah I have been working my way through the help file. It is a ton of information to wrap my head around but I am trying!

I have added print statements to my code so it looks like this:

 
Code
        {
            if (CrossAbove((GetCurrentAsk() + (Offset * TickSize)), SMA(SMAlookback), 1))
			{
				Print("LongCurrentAsk: "+GetCurrentAsk()+" (Offset+Tick): "+(Offset * TickSize)+" SMA: "+SMA(SMAlookback)[0]);
				Print("Calculated value: "+(GetCurrentAsk() + (Offset * TickSize)));
                EnterShort();
			}
            else if (CrossBelow((GetCurrentAsk() + (Offsetneg * TickSize)), SMA(SMAlookback), 1))
			{
				Print("ShortCurrentAsk: "+GetCurrentAsk()+" (Offsetneg+Tick): "+(Offsetneg * TickSize)+" SMA: "+SMA(SMAlookback)[0]);
				Print("Calculated value: "+(GetCurrentAsk() + (Offsetneg * TickSize)));
                EnterLong();
			}
        }
When I look at the output window as the code works I get this:

 
Code
ShortCurrentAsk: 92.94 (Offsetneg+Tick): -0.05 SMA: 92.8932
Calculated value: 92.89
2013-06-04 3:37:38 AM Entered internal PlaceOrder() method at 2013-06-04 3:37:38 AM: BarsInProgress=0 Action=Buy OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='' FromEntrySignal=''
ShortCurrentAsk: 92.94 (Offsetneg+Tick): -0.05 SMA: 92.8932
Calculated value: 92.89
2013-06-04 3:37:39 AM Entered internal PlaceOrder() method at 2013-06-04 3:37:39 AM: BarsInProgress=0 Action=Buy OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='' FromEntrySignal=''
2013-06-04 3:37:39 AM Ignored PlaceOrder() method at 2013-06-04 3:37:39 AM: Action=Buy OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='Buy' FromEntrySignal='' Reason='Exceeded entry signals limit based on EntryHandling and EntriesPerDirection properties'
ShortCurrentAsk: 92.94 (Offsetneg+Tick): -0.05 SMA: 92.8932
Calculated value: 92.89
2013-06-04 3:37:39 AM Entered internal PlaceOrder() method at 2013-06-04 3:37:39 AM: BarsInProgress=0 Action=Buy OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='' FromEntrySignal=''
2013-06-04 3:37:39 AM Ignored PlaceOrder() method at 2013-06-04 3:37:39 AM: Action=Buy OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='Buy' FromEntrySignal='' Reason='Exceeded entry signals limit based on EntryHandling and EntriesPerDirection properties'
ShortCurrentAsk: 92.94 (Offsetneg+Tick): -0.05 SMA: 92.8932
So in that instance the price was above the SMA, at 5 ticks above it went long(which is good!) the output window keeps coming up with this over and over again

 
Code
2013-06-04 3:37:39 AM Entered internal PlaceOrder() method at 2013-06-04 3:37:39 AM: BarsInProgress=0 Action=Buy OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='' FromEntrySignal=''
2013-06-04 3:37:39 AM Ignored PlaceOrder() method at 2013-06-04 3:37:39 AM: Action=Buy OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='Buy' FromEntrySignal='' Reason='Exceeded entry signals limit based on EntryHandling and EntriesPerDirection properties'

Which would mean to me that it keeps getting an order spammed at it that it cannot fill. When in reality all I would like is for it to do nothing until the price moved to 5 ticks below the moving average and have it reverse and go short then.

So basically right now it will do the first entry correctly but it will not reverse for me! :/

Anyways I will keep at it. seems like its a fairly decent sized learning curve but hopefully worth it once I figure it out!

Visit my futures io Trade Journal Started this thread Reply With Quote
 
(login for full post details)
  #12 (permalink)
Wrocław, Poland
 
Experience: Intermediate
Platform: NinjaTrader, Racket
Trading: Ockham's razor
 
gregid's Avatar
 
Posts: 651 since Aug 2009
Thanks: 320 given, 620 received


Trader Chris View Post
 
Code
Reason='Exceeded entry signals limit based on EntryHandling and EntriesPerDirection properties'


Check what are the values for these properties of your strategy in the property grid.

You can change these values in your code as well (in Initialize() ):

 
Code
EntriesPerDirection = 1;
EntryHandling = EntryHandling.AllEntries;

Reply With Quote
The following user says Thank You to gregid for this post:
 
(login for full post details)
  #13 (permalink)
Baltimore MD US
 
Experience: Intermediate
Platform: NinjaTrader
Trading: ES, NQ
 
DeadCatBounced's Avatar
 
Posts: 293 since Apr 2013
Thanks: 1,514 given, 724 received

I havent changed the entries per direction from the default setting which from the webinars I have seen I believe the default value is 1.

I didn't want to change that because at this time I only want can do the one contract at a time! :P

So because I never played with that variable I do not even see it at all in the initialized() area

Visit my futures io Trade Journal Started this thread Reply With Quote
 
(login for full post details)
  #14 (permalink)
OC, California, USA
 
Experience: Advanced
Platform: IB/TWS, NinjaTrader, ToS
Broker: IB, ToS, Kinetick
Trading: stocks, options, futures, VIX
 
shodson's Avatar
 
Posts: 1,958 since Jun 2009
Thanks: 528 given, 3,648 received

First of all, you are using CrossAbove() and CrossBelow() incorrectly. If you look at CrossAbove() for example...

CrossAbove()

You will see that the first parameter needs to be a DataSeries object, not a double. The expression

 
Code
GetCurrentAsk() + (Offset * TickSize)
evaluates to a double, not a DataSeries. I'm surprised your code even compiles! NT's syntactical leniency is the cause of your headaches.

Personally, I've had problems getting these cross methods to work for me sometimes, maybe I was using them incorrectly, but a long time ago I decided to never use them. Now I do something like "if x > y and x wasn't > y in the last bar" logic to determine crosses above.

So if I was to use the Close instead of the ask (not sure why you're using the asking price) it could be

 
Code
SMA sma = SMA(Lookback);
double smaNow = sma[0];
double smaLastBar = sma[1];
double priceNow = Close[0];
double priceLastBar = Close[1];

if (priceNow + (Offset * TickSize) > smaNow && priceLastBar + (Offset * TickSize) <= smaLastBar)
...then we have a cross above scenario

Follow me on Twitter Visit my futures io Trade Journal Reply With Quote
The following user says Thank You to shodson for this post:


futures io Trading Community Platforms and Indicators NinjaTrader > New at Programming, stuck with a crossover strat


Last Updated on June 12, 2013


Upcoming Webinars and Events
 

NinjaTrader Indicator Challenge!

Ongoing
 

Journal Challenge w/$1500 prizes from Topstep!

February
 

Identifying Setups & Targets Using Profile Charts w/Trevor & Tradovate

Feb 25
 

Battlestations! Show us your trading desk - $1,500 in prizes!

March
     



Copyright © 2021 by futures io, s.a., Av Ricardo J. Alfaro, Century Tower, Panama, +507 833-9432, info@futures.io
All information is for educational use only and is not investment advice.
There is a substantial risk of loss in trading commodity futures, stocks, options and foreign exchange products. Past performance is not indicative of future results.
no new posts