NexusFi: Find Your Edge


Home Menu

 





Design a DayTrader Scalping Order Flow Indicator


Discussion in Traders Hideout

Updated
      Top Posters
    1. looks_one hyperscalper with 136 posts (239 thanks)
    2. looks_two Chof with 22 posts (12 thanks)
    3. looks_3 Connor with 16 posts (8 thanks)
    4. looks_4 justtrader with 14 posts (8 thanks)
      Best Posters
    1. looks_one bobwest with 2 thanks per post
    2. looks_two hyperscalper with 1.8 thanks per post
    3. looks_3 SpeculatorSeth with 1 thanks per post
    4. looks_4 Chof with 0.5 thanks per post
    1. trending_up 47,528 views
    2. thumb_up 328 thanks given
    3. group 55 followers
    1. forum 248 posts
    2. attach_file 80 attachments




 
Search this Thread

Design a DayTrader Scalping Order Flow Indicator

  #181 (permalink)
 hyperscalper 
boise idaho
 
Experience: Advanced
Platform: NinjaTrader C# Custom
Broker: NinjaTrader LeeLoo Rithmic
Trading: Nasdaq Futures NQ/MNQ
Posts: 314 since Apr 2020
Thanks Given: 15
Thanks Received: 522

Well, not sure about the code.
But code should be inside a code block to preserve
some of the formatting.
You may need to reconsider some of your design,
since i don't see a really clear idea as to what you
want this code to accomplish...
Enjoy the learning curve

hyperscalper

Started this thread Reply With Quote
Thanked by:

Can you help answer these questions
from other members on NexusFi?
Trade idea based off three indicators.
Traders Hideout
MC PL editor upgrade
MultiCharts
NT7 Indicator Script Troubleshooting - Camarilla Pivots
NinjaTrader
REcommedations for programming help
Sierra Chart
About a successful futures trader who didn´t know anyth …
Psychology and Money Management
 
  #182 (permalink)
 Chof 
Edmonton AB. / Canada
 
Experience: Intermediate
Platform: NT 8
Broker: Amp / CQG
Trading: NQ index
Frequency: Several times daily
Duration: Seconds
Posts: 47 since Apr 2017
Thanks Given: 29
Thanks Received: 50


hyperscalper View Post
Well, not sure about the code.
But code should be inside a code block to preserve
some of the formatting.
You may need to reconsider some of your design,
since i don't see a really clear idea as to what you
want this code to accomplish...
Enjoy the learning curve

hyperscalper

Ohhk... another attempt.. Apologies for not deleting that post (I found out later when I tried that you only have 24 hours to do that).

If this posts as attempted I'd like to send another thank-you to 'BobWest' for his help and extreme patience.

As far as what I want to accomplish - I just want to plot VWAP using the 2 minute "period" as coded - simple. If I want to
do anything else after that I can add that later..

So, thanks and have a good Thanksgiving break HS.

 
Code
//This namespace holds indicators in this folder and is required. Do not change it.
namespace NinjaTrader.NinjaScript.Indicators
{
	/// <summary>
	///  This indicator uses volume data gathered from the "tape".  It uses "OnMarketData"
	///  hence "OMD" from the instantaneous "bid" and "ask" information gathered on every
	///  trade as its published in the "Time and Sales" box as the trades fly by..
	///  
	///  Calculate on BarClose is super important as there could be hundreds of calc's in
	///  every bar to get the final print on the close of the bar (maybe thousands)
	/// 
	///  Also this is probably not going to work properly on historical data..  The data
	///  gathering "asks" won't get all the data from what is kept historically
	/// </summary>
	public class VWAPOMD : Indicator
	{
		protected override void OnStateChange()
		{
			if (State == State.SetDefaults)
			{
				Description					= "Attempt at using OMD volume data to calculate VWAP";
				Name						= "VWAPOMD";
		    	Calculate					= Calculate.OnBarClose;
				IsOverlay					= false;
				IsSuspendedWhileInactive	= false;
				IsAutoScale                                 = true;
				DisplayInDataBox							= true;
				DrawOnPricePanel							= true;
				DrawHorizontalGridLines						= true;
				DrawVerticalGridLines						= true;
				PaintPriceMarkers							= true;
				ScaleJustification							= NinjaTrader.Gui.Chart.ScaleJustification.Right;
				
				AddPlot(Brushes.Yellow,  "vwap");
				    Plots[0].Width = 2;
			}
			
				//else if (State == State.Configure)
	           //else if (State == State.DataLoaded)			
		 }
			// inseert all items in an "outer scope" list
    private List<TradeItem> tradesList = new List<TradeItem>();
	          public class TradeItem {
    public int signedVolume=0;
    public double price = 0.0;
    public DateTime timestamp =  DateTime.UtcNow();
    public TradeItem(int signedVolumeArg, double priceArg) {
           this.signedVolume = signedVolumeArg;
           price = priceArg;
        // automatically timestamped in real time
		
	    // add a trade item (checked for signed volume) into the List
           tradesList.Add(new TradeItem(signedVolume, tradePrice));	
		
		// to trim your list to hold only data within a period of msecs
           long maxAgeInMsecs = 120000; // 2 minutes max age in msecs
        // recent items are added to the end of the list, so let's
        // eliminate any earlier items older than 2 minutes
           DateTime now = DateTime.UtcNow;
           while(tradesList.Count != 0) {
           TradeItem item = tradesList[0]; // first item
           TimeSpan elapsed = ( now - item.timestamp );
        if (elapsed.TotalMilliseconds > maxAgeInMsecs) {
           tradesList.RemoveAt(0); // discard oldest from list; expired, too old
    }
      else {
           break; // assuming all further data is OK
    }
}
		
		   double sumPV =0.0;
           double sumV = 0.0;
foreach    ( TradeItem item in tradesList) {
     //    example of positive volumes only
     if    (item.signedVolume>0) { // positive numbers only
           double absVolume = Math.Abs(item.signedVolume);
           sumPV += ( item.price * absVolume);
           sumV += absVolume;
		 
		   // a zero return PRICE means no data
		   double vwap = sumV==0 ? 0 : sumPV / sumV;
		   //parent.ninjaPrint2("vwap data items: "+n+" price: "+vwap);
		   return vwap;	 
     }
}
// now you have what you need for the VWAP		
	}			  		
		protected sealed override void OnMarketData(MarketDataEventArgs dataPacket) {

    MarketDataType type = dataPacket.MarketDataType; 

    if ( type == MarketDataType.Last) { 
         
        
         double price = dataPacket.Price; 
         double bidPrice = dataPacket.Bid; 
         double askPrice = dataPacket.Ask; 
         double midPrice = 0.5 * ( bidPrice + askPrice ); 
         int tradeLotSize = (int)dataPacket.Volume; 
         if ( tradePrice < midPrice ) { 
              (int) signedVolume =  (int) tradeLotSize ;
         }
         else {
              (int) signedVolume = (int) tradeLotSize * -1 ;
         }
 
	}
    

	}
	
			  
		protected override void OnBarUpdate()
		{
		    	if (CurrentBar < 1) 
				return;
		}

		#region Properties
		#endregion
			  
			  }
	}
}


Chuck

Reply With Quote
Thanked by:
  #183 (permalink)
 hyperscalper 
boise idaho
 
Experience: Advanced
Platform: NinjaTrader C# Custom
Broker: NinjaTrader LeeLoo Rithmic
Trading: Nasdaq Futures NQ/MNQ
Posts: 314 since Apr 2020
Thanks Given: 15
Thanks Received: 522



Chof View Post
Ohhk... another attempt.. Apologies for not deleting that post (I found out later when I tried that you only have 24 hours to do that).

If this posts as attempted I'd like to send another thank-you to 'BobWest' for his help and extreme patience.

As far as what I want to accomplish - I just want to plot VWAP using the 2 minute "period" as coded - simple. If I want to
do anything else after that I can add that later..

So, thanks and have a good Thanksgiving break HS.


Chuck

Oooo-Kay, Chuck.

First of all I can't do a detailed markup of all the issues
in that code.

However, C# is an "object oriented" programming language.
And I defined a "data item capture class" called TradeItem.

This is defined as a "class", e.g.:

 
Code
public class TradeItem {
}
For every single (signed) Trade which is incoming, a new
instance of TradeItem is created, and Added to the tradesList,
which is a list of TradeItem objects instances, e.g.
List<TradeItem> tradesList = new List<TradeItem>();

I wouldn't think your code will even compile, unless TradeItem is
a class, rather than a function/method definition as you have
it. the "new" keyword works only with a class as an operand.

[edit] There may be some C# "weirdness" in which the word
"class" is not required; but I would avoid such a thing. There
are a lot of C# constructs which "work" but in this case, when
you are defining a class or struct which will be instantiated
multiple times, you use "class" or "struct" just in case the
intent is not clear. I'm a Java programmer at heart; so certain
C# constructs or short-hand, I just don't use.

[edit2] You're not just a guy sent to test me, right? LOL just kidding...
From your code it looks to me like not only is "class" not used
in defining TradeItem, but inside the definition of TradeItem
you're instantiating a new TradeItem(...). But you are a real
person, and not just trolling, right? again, just kidding.

I don't see most of those concepts, or that you are using the
"new" operator to create a new TradeItem on each trade in your code.
(I could be wrong here; but you are improving, and I'm encouraging
you to keep improving your skills in modelling the objectives of
this Indicator you want to create.)

So, in addition to "scoping" concepts; you should look into the
"object oriented" features of C# so that you fully understand all
that; and then take your design further.

AND WHILE I HAVE YOUR ATTENTION
Consider that if you calculate a VWAP (unsigned) for Trades, and
you Plot that; or even also plot a Simple average against it (which
is basically just the avg(Price) itself, each Price weighted as 1); and
perhaps even calculate a "delta" (difference) between the two, etc....
You need to have an overall reason for doing all this, based on a theory.

What is being measured, and why could it be predictive of Price movement?

For example, if you did a moving (2 minute, or whatever) window
calculation of even an UNSIGNED VWAP (for all trade volumes) and
you plotted it against a Simple Average; and then PLOTTED
the DELTA ( VWAP - SAP ) * Multiplier ... that you might get an
interesting Delta value to track, which would alternate between
positive and negative values around zero.

We know that Larger Trade Volumes, and a Higher Rate of those
Volumes, will occur at both Tops and Bottoms. Therefore, your
Moving VWAP would, in fact show a +/- Delta which (when magnified),
would identify Tops and Bottoms to some extent. That's because
a VOLUME-WEIGHTED average Price will be "pulled" toward the
higher-weighted Volume@Price events

That's what you would find with such an algorithm. Now, is that enough
for you; and how could you improve things? Your goal is to identify a
Top Price and a Bottom Price for Trend Reversals, I would assume...

But, before you can do any of that, you need to master the C# language,
and Object-Oriented concepts; then take things further. Hope this helps !

hyperscalper

Started this thread Reply With Quote
  #184 (permalink)
 Chof 
Edmonton AB. / Canada
 
Experience: Intermediate
Platform: NT 8
Broker: Amp / CQG
Trading: NQ index
Frequency: Several times daily
Duration: Seconds
Posts: 47 since Apr 2017
Thanks Given: 29
Thanks Received: 50

Hi HC,

I agree, defining the "class" has to be first (clearly I wasn't thinking).
Even my limited "CS" education taught me that. I've done that
 
Code
	          public class TradeItem {
    private List<TradeItem> tradesList = new List<TradeItem>();
but the errors are the same.. "OnMarketData" and "OnBarUpdate" no
suitable method found to override..

I used the code snippets you posted exclusively. I did however, take code
from the first that you shared to define the method to add a sign to the volume.
What's apparent to me if the code you shared is written properly
(which I don't doubt it is - maybe a typo here or there) then, the order I've
used it in is probably wrong and that's because I haven't learned the
methods described here:
 
Code
So, in addition to "scoping" concepts; you should look into the
"object oriented" features of C# so that you fully understand all
that; and then take your design further.
If you can believe this I did take a course in C# that used the Microsoft editor, but,
it only taught about adding objects from a menu. The structure was already in the
code with headings before you started, so knowing what to put where was never taught.
So, if you share a source other than CS 303 where I could learn about "scope" and
"object oriented - specifically order placement of code" - I'm all ears.

Oh, on the subject of where to go when this compiles, I am positive you're giving
good (probably great) advice. I've already hinted of what the leads are that tell me of
market direction and direction changes. It will be an exciting thing to get all that
coded together, but I doubt either of us is going to share everything we actually use.
The truth is, the basis of our code is probably already in this thread.

Thanks again HS,

Chuck

Reply With Quote
  #185 (permalink)
 hyperscalper 
boise idaho
 
Experience: Advanced
Platform: NinjaTrader C# Custom
Broker: NinjaTrader LeeLoo Rithmic
Trading: Nasdaq Futures NQ/MNQ
Posts: 314 since Apr 2020
Thanks Given: 15
Thanks Received: 522

INNER CLASSES and Garbage Collection

It seems that a lot of coders have a reluctance
to use multiple class definitions; and it's not
easy to write "big code" in a single file, which is
basically what you have to do in the NinjaScript
Editor...

An "inner class" definition can be done anywhere
in code, and should be at the outer scope normally,
sitting within the Indicator class outer block.

I"m sure you know that just as Java runs on a
Virtual Machine (VM); that C# runs on Microsoft's
Common Language Runtime (CLR) VM.

Microsoft calls this "managed code". And it means,
it's much easier to allocate and de-allocate memory,
since it has Garbage Collection which is very
efficient.

Traditional programmers don't really understand
these things, that a "new TradeItem(...)" can be
placed in a list; and then when it's removed from
the List, WHERE DOES IT GO?

Well, of course, mechanisms like "reference counting"
ensure that if an object has NO references at all,
that it is "Garbage Collected" efficiently by the VM.

So, we we "trim" the List<TradeItem> by removing
elements, and Add "new TradeItem" elements, then
all that ADDED MEMORY ALLOCATED, is ultimately
going to use up ALL OF THE MEMORY, since there
is NOWHERE in the code where we de-allocated
all those TradeItem instances !!!!!

This means your code can only run so long; until you
exhaust memory; so that's not great, is it ?? What's
a programmer to do ???

LOL, of course, Garbage Collection automaGically
reclaims and re-uses memory; so long as nothing
"hangs onto" (i.e. references an object) that
memory.

The struct definition is the "template" for a "struct",
or in the new terminology a "class" definition is
the "cookie cutter" template for an object, which
can have many capabilities beyond the concept of
a "struct".

Of course a "class object" combines the idea of
(struct-like) private Data along with the idea of Code which is bound
to that data instance, and of course that can be multi-threaded
in execution as well.

But nobody had to explain that, right ??? lol
Cuz you understood all of that, I hope.

NinjaTrader 8 is so advanced because it opens up the
concepts of Object Oriented design, Multi-Threading
and extremely fast execution, within a Virtual Machine
which makes the system robust, and "uncrashable"
because the VM is "managed code", etc.....
WE LIVE IN AN AGE OF MIRACLES; so take advantage of
it all !!! but you knew that already, right?

hyperscalper

Started this thread Reply With Quote
Thanked by:
  #186 (permalink)
 OpalDragon 
Des Moines, Iowa
 
Experience: Advanced
Platform: Ninja Trader
Trading: 6E, CL, Anything that moves
Posts: 559 since Jun 2012
Thanks Given: 733
Thanks Received: 232

Guys -- I have just started reading this thread -- but -- I have an important question.

Why are you running an ORDER FLOW Indicator / Study on a TIME BASED CHART? ?

I think that is a BIG MISTAKE because my belief / theory / hypothesis on this matter is that time is an ARBITRARY MEASUREMENT for orderflow based studies.

You want bars to move purely based on price action.

Ticks
volume
1-Tick Range candles -- yes 1 tick NO Gap Range Bars

Some Renkos?

Other custom bars -- that are run purely on price data and not time

LogikTickX Bar from Pure Logik


I wonder if you would make more progress with other type of bars as a starting point.

Reply With Quote
Thanked by:
  #187 (permalink)
 hyperscalper 
boise idaho
 
Experience: Advanced
Platform: NinjaTrader C# Custom
Broker: NinjaTrader LeeLoo Rithmic
Trading: Nasdaq Futures NQ/MNQ
Posts: 314 since Apr 2020
Thanks Given: 15
Thanks Received: 522


OpalDragon View Post
Guys -- I have just started reading this thread -- but -- I have an important question.

Why are you running an ORDER FLOW Indicator / Study on a TIME BASED CHART? ?

I think that is a BIG MISTAKE because my belief / theory / hypothesis on this matter is that time is an ARBITRARY MEASUREMENT for orderflow based studies.

You want bars to move purely based on price action.

Ticks
volume
1-Tick Range candles -- yes 1 tick NO Gap Range Bars

Some Renkos?

Other custom bars -- that are run purely on price data and not time

LogikTickX Bar from Pure Logik


I wonder if you would make more progress with other type of bars as a starting point.


The algorithm in this thread cumulates continuous Trade Flow (T&S) events over
a Moving Window FIXED period of time, regardless of the Bar format being used,
so completely independent of that.

Please explain then why it should matter what Bar type is being used, except
that it would affect the visualiz(s)ation of the resulting Net Inventory ?

hyperscalper

Started this thread Reply With Quote
Thanked by:
  #188 (permalink)
 satori33 
hialeah florida/eua
 
Experience: Intermediate
Platform: ninjatrader
Trading: emini es
Frequency: Every few days
Duration: Minutes
Posts: 2 since Mar 2019
Thanks Given: 12
Thanks Received: 0

hi everyone, it could be added to the hyperscalper indicator, an alert as a window, or sound when a biglot appears?

Reply With Quote
  #189 (permalink)
 hyperscalper 
boise idaho
 
Experience: Advanced
Platform: NinjaTrader C# Custom
Broker: NinjaTrader LeeLoo Rithmic
Trading: Nasdaq Futures NQ/MNQ
Posts: 314 since Apr 2020
Thanks Given: 15
Thanks Received: 522


satori33 View Post
hi everyone, it could be added to the hyperscalper indicator, an alert as a window, or sound when a biglot appears?

Things like that are "easy".

The hard part is deciding how not to get
"too many" or "too few" such Alerts.
And, just what are peeps going to do,
when an Alert happens?

It's like "crying wolf" too many times.

And if you give "the People" Alerts, they will
most likely not be responding to them; so,
in the end, you're just doing work for no
real gain.

I've described TradeFlowRisk as a "situational
awareness" indicator. With such an indicator,
you should have a heightened awareness that
"Market Maker may be preparing for a turn
in trend".

I can easily give sounds; but it's not for me to
keep enhancing things; I started the thread to
discuss concepts. The implementation is provided
to encourage more of you to take a deep dive, and
learn how to implement your Brilliant Ideas (tm)
into code.

PRO TIP: When I am writing or enhancing an
indicator, I ask myself "Will this be Pretty, or
will it make me Money"? Is it necessary and
effective? So many of you have "Itchy Clouds"
and fancy such indicators; but how is it that
they actually contribute to your Bottom Line? lol

hyperscalper

Started this thread Reply With Quote
Thanked by:
  #190 (permalink)
 Chof 
Edmonton AB. / Canada
 
Experience: Intermediate
Platform: NT 8
Broker: Amp / CQG
Trading: NQ index
Frequency: Several times daily
Duration: Seconds
Posts: 47 since Apr 2017
Thanks Given: 29
Thanks Received: 50


 
Code
INNER CLASSES and Garbage Collection

(Yesss.. yes this is exactly how we start learning)

It seems that a lot of coders have a reluctance
to use multiple class definitions; and it's not
easy to write "big code" in a single file, which is
basically what you have to do in the NinjaScript
Editor...  (Yep -Reluctance &
not easy)


An "inner class" definition can be done anywhere
in code, and should be at the outer scope normally,
sitting within the Indicator class outer block.

I"m sure you know that just as Java runs on a
Virtual Machine (VM); that C# runs on Microsoft's
Common Language Runtime (CLR) VM. (No - 
never had a clue)

Microsoft calls this "managed code". And it means,
it's much easier to allocate and de-allocate memory,
since it has Garbage Collection which is very
efficient.

Traditional programmers don't really understand
these things, that a "new TradeItem(...)" can be
placed in a list; and then when it's removed from
the List, WHERE DOES IT GO?

Well, of course, mechanisms like "reference counting"
ensure that if an object has NO references at all,
that it is "Garbage Collected" efficiently by the VM.

So, we we "trim" the List<TradeItem> by removing
elements, and Add "new TradeItem" elements, then
all that ADDED MEMORY ALLOCATED, is ultimately
going to use up ALL OF THE MEMORY, since there
is NOWHERE in the code where we de-allocated
all those TradeItem instances !!!!!

This means your code can only run so long; until you
exhaust memory; so that's not great, is it ?? What's
a programmer to do ???

LOL, of course, Garbage Collection automaGically
reclaims and re-uses memory; so long as nothing
"hangs onto" (i.e. references an object) that
memory.

The struct definition is the "template" for a "struct",
or in the new terminology a "class" definition is
the "cookie cutter" template for an object, which
can have many capabilities beyond the concept of
a "struct".

Of course a "class object" combines the idea of
(struct-like) private Data along with the idea of Code 
which is bound to that data instance, and of course that 
can be multi-threaded in execution as well.

But nobody had to explain that, right ??? lol
Cuz you understood all of that, I hope.
Umm, wasn't too concerned about
memory if it worked - but this is good to know.  The "class" 
and "class object" definitions are much appreciated and YES
definitely somebody needs to describe it this way to be able to
understand your next posts. I hope so too. :) 

NinjaTrader 8 is so advanced because it opens up the
concepts of Object Oriented design, Multi-Threading
and extremely fast execution, within a Virtual Machine
which makes the system robust, and "uncrashable"
because the VM is "managed code", etc.....
WE LIVE IN AN AGE OF MIRACLES; so take advantage of
it all !!!  but you knew that already, right? I did know 
that NT could utilitze multi-threading.  I was half
hoping that running loops before 'OnBarUpdate' was exactly 
that.  Was I correct? Does that define what we're doing in this
type of code?

Reply With Quote
Thanked by:




Last Updated on January 26, 2023


© 2024 NexusFi™, s.a., All Rights Reserved.
Av Ricardo J. Alfaro, Century Tower, Panama City, Panama, Ph: +507 833-9432 (Panama and Intl), +1 888-312-3001 (USA and Canada)
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.
About Us - Contact Us - Site Rules, Acceptable Use, and Terms and Conditions - Privacy Policy - Downloads - Top
no new posts