lbf4223 Posted June 24, 2018 Report Share Posted June 24, 2018 (edited) Over the course of the next several weeks (months if there's continued, enthusiastic interest), I'd like to show you how I organize an NT7 Strategy. The emphasis in the coding is going to be more focused on organization and readability rather than what would necessarily be the most straightforward or optimal way of coding it. I'm pretty sure the audience I'm trying to reach here hasn't come from a professional coding background so "simple" goes a lot farther to understanding how to write an NT Strategy than "clever" ever will. What I'll do is post the Strategy on an incremental basis with each post making more and more progress towards some goal(s). In most instances, the delays in postings are not from me having to take the time to code anything new for the Strategy, but rather to pull the pieces out of code from other files I have which are far more involved than I am planning to present here. Here's the progressive plan. Each number below represents a major milestone to accomplish and there will be follow-up posts for each one to explain the details: 1. Show the basic Strategy template code. There is no Strategy to execute trades against on this first posting. It will be an opportunity to look at the shell of what is to come. It's primarily a lot of C# methods which need to be filled in later; however, they're surrounded by C# regions which you can fold/unfold in the NinjaScript editor and, over time, you'll find that very useful to get around the Strategy as it grows. Things won't feel so overwhelming because you already have enough organization setup to know where to go looking for the changes you want to make. 2. I'll add the logic to go long/short a simple bar close above above/below a 9 wma (weighted moving average) and also how to go long/short when price first closes above/below a 9 wma and then it taps the 9 wma on a pullback. From this, you will see two ways of entering a trade: the first is on a bar close and the second is an incoming tick when it touches something based on a prior event having occurred (in this case, price closing through the 9 wma first). NinjaTrader's "Managed Approach" to order entry/exit will be demonstrated. 3. I'll add some items to the toolbar above the chart so you can manage the target / stop for each trade and you'll be able to close the trade instantly by pressing the ESC if you want. 4. I'll add actual lines on the chart in an open trade where you can move the target or stop manually with the a shift key / left mouse button combo. 5. Open-ended. We'll see what happens next, maybe auto-adjusting stop management or conditions to ADD to winning trades? I have no interest in peeling off contracts from a winning trade (aka multiple targets) or continually adding to a losing position. This is an offer to everyone for a hand-up in your trading toolbox, not a hand-out. If you have no interest in coding your own Strategies then this thread is definitely not for you. This won't be a fully automated Strategy development tutorial. It's more semi-automated. You decide when it's the right context to take your signal and then let the computer take the entry for you. I tend to manage trades by my own hand but I can code up an auto-adjusting stop as an example. The actual decision in code to take an entry is trivial most of the time, one or two simple decisions, that's it! It's all the coding infrastructure required to facilitate that that's the tedious part. The Strategy template code is an attachment that you can download at the bottom of this message. There's no need to post it to some other site. It's non-proprietary code that I have created and am freely giving you to for your own personal use. You can import the zip file using NT 7's import NinjaScript tool. It will compile...and do nothing yet. That's the point initially...for you to look at the code in the NinjaScript editor, fold/unfold the various "#region / #endregion" code segments so you can see the basic organization of what is to come in subsequent posts. One thing that I do ask of everyone is no private messages concerning any techniques talked about here. Anything that needs to be further detailed should be posted for all to see. The "education" in this thread is the other kind we all first learned...for your mind. DISCLAIMER: The code posted here is for demonstration purposes only, to be used in a simulation environment for your personal education as trading examples. I am not a trading vendor, make no guarantees of either the reliability or durability of this sample code under real-time market conditions, no matter what degree of market volatility is present and take no responsibility for your choice to use this demonstration code in a live market where your money will be at high risk.IndoDemoStrategy.zip Edited July 1, 2018 by lbf4223 Added IndoDemoStrategy.zip file alyzar, shickman, Traderbeauty and 15 others 18 Quote Link to comment Share on other sites More sharing options...
shickman Posted June 24, 2018 Report Share Posted June 24, 2018 lbf4223 wow this is great at last something to look forward on this almost dead thread :) thank you Quote Link to comment Share on other sites More sharing options...
thedriver Posted June 24, 2018 Report Share Posted June 24, 2018 ------ One thing that I do ask of everyone is no private messages concerning any techniques talked about here. Anything that needs to be further detailed should be posted for all to see. The "education" in this thread is the other kind we all first learned...for your mind. *** Well said mister lbf4223!!!=D>=D> shickman 1 Quote Link to comment Share on other sites More sharing options...
lbf4223 Posted June 24, 2018 Author Report Share Posted June 24, 2018 (edited) It's probably best upfront if I go over some of the structure and content of the template Strategy C# file I posted in the first message. These areas will grow in code but the initial template has what I consider to be the absolute bare minimum for setup in the way I would want to structure a trade. Here's the extracted code from the Initialize() method: protected override void Initialize() { // NinjaTrader Global Settings (see NinjaScript documentation) CalculateOnBarClose = false; DefaultQuantity = 1; Enabled = true; EntriesPerDirection = 1; EntryHandling = EntryHandling.AllEntries; StopTargetHandling = StopTargetHandling.ByStrategyPosition; TraceOrders = false; // Initial Property Settings for Strategy MinTicksBetweenAdds = 10; DefaultTarget = 50; DefaultStop = 10; Stop = 10; Target = 50; } The properties set just under the "// NinjaTrader Global Settings" area I use are all documented in the NT7 Help Guide [except "StopTargetHandling"] (press F1 when you're in the NinjaScript editor and the guide will popup in another window for you to peruse). In summary though, the way I've set things up are: 1. Enable the Strategy immediately once you insert it into a chart. Don't worry, no trades will ever be allowed to execute without your expressed permission because long/short variables will have to be turned on in order to even begin considering an entry. They're always turned off by default. 2. Since I'm using NT's Managed Approach trading routines, they give you a nice way of protecting yourself from entering too many signals in the same direction. When EntriesPerDirection is set to 1, NT will only allow you to have 1 position, no matter how many long or short signals you try to send in your code. Once you hit the limit set by EntriesPerDirection, that's it, all other attempts to add positions to the current trade will be ignored. That's a VERY good thing! 3. In Managed Approach mode, if you take multiple positions, you have the choice of each new position having its own stop/target bracket orders OR you can have each new position have its stop/target bracket orders collect at the first order's bracket. Since I'm an all-out style trader (even when adding to a winning initial trade), I'm going to go with the former approach...collection of all stops/targets matching the 1st order and then I'll move the stop and target around for all the contracts I have in the open trade. Imagine if you had 4 separate entries of 1 contract each in 1 trade sequence and each one had a separate stop and target bracket set based on each one's entry. Personally, that would be too stressful for me to handle in a fast, real-time market, way too much manual manipulation to get out of 4 positions, and, like I mentioned before, I prefer more of a manual approach to exit than automated. ------------- Note: What I want and you want out of our trading may be 180 degress apart. That's fine. The code is here for you to modify to your heart's content. All I can do is show you what I prefer and talk about that as a basis for learning. ------------- 4. The settings below the comment line, "// Initial Property Settings for Strategy" (btw, in C#, anything on a line which follows two forward slashes together are how to add one-line comments to your code) are entering in to the world of MY property settings, not what NT provides. Really important distinction here: NT provides a way for you to create your own properties for a Strategy and you can display/change them when you initially add a new Strategy to your chart. You can also setup default values which survive separate instantiations of your Strategy as I think most of you already know how to do by right clicking any property value you change and then clicking on their save as default little popup window "Set Default For <property name>". Cool beans. HOWEVER, NT doesn't want you changing any of your own properties from that initial settings window WHILE your Strategy is set to Enabled ("Enabled = true;" in the Initialize() method or setting Enabled to True in the Properties Window when adding the Strategy to your chart). What I prefer to do is expose all of my properties for the real-time trading purposed here so I can darn well change them whenever I want. More on this to come much later as the demo Strategy starts to gain functionality. Okay, that said, some initial values I place in the Initialize() section for my properties are not really important. They're more like placeholders which will change before any actual trade is taken. The Stop and Target properties will apply to the current trade. The DefaultStop and DefaultTarget properties are the values which Stop and Target will be reset to once the trade is exited. The reason for this is so the adjustments I make to Stop/Target for an ongoing trade will not affect the next new trade sequence I take. Upon exit of a current trade, part of the "reset routine" will be to assign Stop back to DefaultStop and Target back to DefaultTarget. That's the automatic part done for you. You can still manually set the Stop/Target to different values before taking the next trade from the preexisting toolbar above your chart. Much, much later in the series, if all of you are chanting, "more, more, MORE", we can get into highly customized toolbars which can reside below the default one you see on every chart. Finally, the "MinTicksBetweenAdds = 10;" is my property which will require all add-on trades to an initial trade to be a minimum of 10 ticks apart; otherwise, the signal to add to my trade will be ignored. The ignoring of too many signals too close together is A WONDERFUL THING! NT provides the facility to limit how many separate positions you can have in one trade sequence and what I'm doing is enforcing that any trade added to that trade sequence must have enough breathing room between entry signals so you don't over-leverage yourself to where the slightest of retraces could find you panicing to get out EVEN THOUGH you were right to continue to be bullish or bearish in the respective trend. I'll continue in another post to outline some other decisions I made in the Strategy template code posted in #1. Edited June 25, 2018 by lbf4223 tradermic, ⭐ ESVepara, Albnd and 4 others 7 Quote Link to comment Share on other sites More sharing options...
supertrade Posted June 24, 2018 Report Share Posted June 24, 2018 A really very good initiative from you, ibf. Thank you for this thread, I will be following this. Quote Link to comment Share on other sites More sharing options...
Billy1960 Posted June 29, 2018 Report Share Posted June 29, 2018 Hello, If I want to insert the code to any strategy I choose to execute opposite orders from what the signial is saying is there a paspartou code I can insert to any strategy and in which position ? Thank you in advance for your efforts. Quote Link to comment Share on other sites More sharing options...
lbf4223 Posted June 29, 2018 Author Report Share Posted June 29, 2018 Hello, If I want to insert the code to any strategy I choose to execute opposite orders from what the signial is saying is there a paspartou code I can insert to any strategy and in which position ? Thank you in advance for your efforts. No, there's no level of indirection or global flag of some sort which would switch the meaning of a buy to a short or a short to a buy. You would have to have the source code and directly change the buy signals to short signals and vice verse. Billy1960 and ⭐ laser1000it 2 Quote Link to comment Share on other sites More sharing options...
Billy1960 Posted June 30, 2018 Report Share Posted June 30, 2018 (edited) Can I please you to insert this specific code in blu @e w@ve strategy to run a test to this super losing strategy lol. https://www.sendspace.com/file/7qhwo2 I have big curiosity for the results Thank you B Edited June 30, 2018 by Billy1960 ⭐ laser1000it 1 Quote Link to comment Share on other sites More sharing options...
⭐ laser1000it Posted June 30, 2018 Report Share Posted June 30, 2018 (edited) Can I please you to insert this specific code in blu @e w@ve strategy to run a test to this super losing strategy lol. https://www.sendspace.com/file/7qhwo2 I have big curiosity for the results Thank you B Thanks . This is a good request. Anyway if the BWT result is super losing, why don't you do the reversee ? When the strategy is Long you go Short and viceversa. Edited June 30, 2018 by laser1000it Quote Link to comment Share on other sites More sharing options...
Billy1960 Posted June 30, 2018 Report Share Posted June 30, 2018 (edited) The strategy is a trending one has nice automation features one of them is to see quickly the result in 45 depth period in the bottom left result ,increase decrease sesnsitivity and some more.EG if you put it in high sensitivity in a a daily constant ranging period (when most of the global players sleep deep and there are not any fundamental news ?) it will loose bigtime . Edited June 30, 2018 by Billy1960 Quote Link to comment Share on other sites More sharing options...
lbf4223 Posted June 30, 2018 Author Report Share Posted June 30, 2018 Now, still on the original code posted in #1, I'm going to go over different sections of it so you can get a good idea of the overall structure of this Strategy template code. Open up the IndoDemoStrategy Strategy in NinjaScript and have all of the parts of the code sections folded like this below. By "fold", I mean that all of the C# code between #region / #endregion are hidden like so (yes, I see the typos in the C# comments of the code. I'll fix that): tradershare, ⭐ laser1000it and Billy1960 3 Quote Link to comment Share on other sites More sharing options...
lbf4223 Posted June 30, 2018 Author Report Share Posted June 30, 2018 Next, open up the "Variables" region. I have a few variables declared to be global to the Strategy. Global just means that every other method in the strategy can see and modify them as the Strategy runs. What we run across a lot in developing either strategies or indicators is having to compare two floating point values. Floating point values cannot be directly compared with one another with perfect precision because there can be some very small rounding errors found way out from the right of the decimal point. This means you cannot directly compare the equality of two floating point values in C#. You could have what looks like the same value but a very small rounding error would show them as not equal to each other in a direct comparison (even though they are). To get around this, NinjaScript provides a method called MasterInstrument.Compare() when you're trying to compare two prices. The prices will be compared by accuracy according to the TickSize of the instrument you're Strategy is running under. I get around all of this by simply using C#'s built-in decimal type in place of float or double types. Decimal types can be compared with absolute precision so I convert any float or double types to compare to decimal and there's none of these rounding error problems. Ease of readability is the goal here and any slowness incurred by using decimal types is completely unimportant in the context of running a Strategy. Below, I define a tickValue and a tickSize. tickValue will be filled in with the dollar amount of 1 tick of the Strategy's primary instrument. tickSize will be NinjaScripts decimal version of their global variable called TickSize. Next are some string values for labeling entries and exits to trades. Then, I have to declare some global order entry variables of type IOrder to hold pointers to the current entryOrder, targetOrder and stopOrder. NinjaScript's trade routines are going to require these to be passed into them so it knows which order you're dealing with to change in some way. The last variable declared is a stack of decimal numbers representing all of the entries a trade sequence has currently taken. There's, of course, the original trade entry, and then any add-ons taken as the trade moves your way. Billy1960 1 Quote Link to comment Share on other sites More sharing options...
lbf4223 Posted June 30, 2018 Author Report Share Posted June 30, 2018 I've already talked about the Initialize() method. The next set of methods are the OnStartup() and OnTermination(). They get called just before the first OnBarUpdate() call is made and just before the Strategy is removed from your chart, respectively. Examples of what you would put in OnStartup() would be: 1. Initializing your property variables. I defined my own at the bottom of the IndoDemoStrategy and will initialize them in OnStartup(). There are times when a Strategy can get reloaded but the Initialize() method will not be called. 2. Starting up a Timer which can be used to asynchronously wake-up perform some action independent of an incoming tick calling the OnBarUpdate() method. 3. Adding some user interface controls to the existing Toolbar Control above the price chart creating your own custom toolbar added below the one above the price chart or even adding your own pop-up window which can contain any level of complexity you want to be able to control your Strategy in real-time. Examples of what you would put in OnTermination() would be: 1. Stopping a Timer you had started in OnStartup(). 2. Removing any user interface controls you had added in OnStartup. Billy1960 and tradershare 2 Quote Link to comment Share on other sites More sharing options...
lbf4223 Posted July 1, 2018 Author Report Share Posted July 1, 2018 (edited) In Post #1, I have now attached the initial IndoDemoStrategy Strategy as an NT 7 importable zip file and removed the sendspace location. There's no need to post this template or any changes I make to it in the future to another website. It's better that it stays easily accessible here in this forum so that what you need is all here. The code will not be referencing anyone else's proprietary information and and I have no problem with the code I created / add to it in the future being used for your personal interests. It's just that I don't carry the responsibility / liability of any losses you may incur from it in a live account, blah, blah, blah. You know the drill. I may be going too slow for some of you in these posts but, later on, when things get more involved instead of having to hunt me down for an answer, you can get from some prior post in this thread. The details will have value and save you time as the complexity increases. Edited July 1, 2018 by lbf4223 Billy1960 1 Quote Link to comment Share on other sites More sharing options...
⭐ laser1000it Posted July 1, 2018 Report Share Posted July 1, 2018 Can I please you to insert this specific code in blu @e w@ve strategy to run a test to this super losing strategy lol. https://www.sendspace.com/file/7qhwo2 I have big curiosity for the results Thank you B Anyway i don't understand why I have to change/modify a code. If I buy a strategy the code must remain as it is. Is the platform that has to be adapted. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.