Пример #1
0
 public static decimal[] Opens(BarList chart)
 {
     List<decimal> l = new List<decimal>();
     foreach (Bar b in chart)
         l.Add(b.Open);
     return l.ToArray();
 }
Пример #2
0
 /// <summary>
 /// The lowest low for the barlist, considering so many bars back.
 /// </summary>
 /// <param name="b">The barlist.</param>
 /// <param name="barsback">The barsback to consider.</param>
 /// <returns></returns>
 public static decimal LL(BarList b, int barsback)
 { // gets lowest low
     if (barsback > b.Count) barsback = b.Count;
     decimal ll = decimal.MaxValue;
     for (int i = b.Last; i > (b.Count - barsback); i--) ll = (b.Get(i).Low < ll) ? b.Get(i).Low : ll;
     return ll;
 }
Пример #3
0
 /// <summary>
 /// Returns the highest-high of the barlist, for so many bars back.
 /// </summary>
 /// <param name="b">The barlist.</param>
 /// <param name="barsback">The barsback to consider.</param>
 /// <returns></returns>
 public static decimal HH(BarList b, int barsback)
 {// gets highest high
     if (barsback > b.Count) barsback = b.Count;
     decimal hh = decimal.MinValue;
     for (int i = b.Last; i > (b.Count - barsback); i--) hh = (b.Get(i).High > hh) ? b.Get(i).High : hh;
     return hh;
 }
Пример #4
0
        public bool newBar(BarList bl)
        {
            if (!bl.isValid) return false;
            Bar obar = bl.Get(bl.Last);
            if (!isbarcons) throw new Exception("You can't call a newBar method without using the right constructor.");
            if (bl.NewBar)
                {
                    count++;
                    decimal open = obar.Open;

                    l.Add(open);

                    if (l.Count > lookback)
                    {
                        l.RemoveAt(0);
                        count--;
                    }

                    sum = 0;
                    sumsqtrade = 0;
                    foreach (decimal v in l)
                    {
                        sum += v;
                        sumsqtrade = sumsqtrade + v * v;
                    }
                    mean = sum / count;
                    devavg = (sumsqtrade - sum * sum / count) / count;
                }


                sd = Math.Sqrt((double)devavg);
                ub = mean + sds * (decimal)sd;
                lb = mean - sds * (decimal)sd;
                return true;
        }
Пример #5
0
 /// <summary>
 /// Provide this chart with a new barlist, and refresh the display.
 /// </summary>
 /// <param name="barlist">The barlist.</param>
 public void NewBarList(BarList barlist)
 {
     bl = barlist;
     Symbol = bl.Symbol;
     Text = Title;
     Refresh();
 }
Пример #6
0
        public void NewBars()
        {
            BarList bl = new BarList(BarInterval.FiveMin);
            int newbars = 0;
            foreach (Tick k in ticklist)
            {
                bl.newTick(k);
                if (bl.NewBar)
                    newbars++;
            }

            Assert.That(newbars == 2, newbars.ToString());


            bl = new BarList(BarInterval.Minute);
            newbars = 0;
            foreach (Tick k in ticklist)
            {
                bl.newTick(k);
                if (bl.NewBar)
                    newbars++;
            }

            Assert.That(newbars == 8, newbars.ToString());

        }
Пример #7
0
 /// <summary>
 /// Provide this chart with a new barlist, and refresh the display.
 /// </summary>
 /// <param name="barlist">The barlist.</param>
 public void NewBarList(BarList barlist)
 {
     bl     = barlist;
     Symbol = bl.Symbol;
     Text   = Title;
     Refresh();
 }
Пример #8
0
 public decimal AvgVol(BarList bl) // gets the average volume across all bars
 {
     if (!bl.Has(MinimumBarsToAvg)) return 0; // if we don't have a bar yet we can't have an avg bar volume
     int sum = 0;
     for (int i = 0; i < bl.Count; i++)
         sum += bl[i].Volume;
     return sum / (bl.Count);
 }
Пример #9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Chart"/> class.
 /// </summary>
 /// <param name="b">The barlist.</param>
 /// <param name="allowtype">if set to <c>true</c> [allowtype] will allow typing/changing of new symbols on the chart window.</param>
 public Chart(BarList b,bool allowtype)
 {
     InitializeComponent();
     bl = b;
     Symbol = b.Symbol;
     Paint += new PaintEventHandler(Chart_Paint);
     MouseWheel +=new MouseEventHandler(Chart_MouseUp);
     if (allowtype) this.KeyUp += new KeyEventHandler(Chart_KeyUp);
 }
Пример #10
0
 protected override Order ReadOrder(Tick tick, BarList bl, BoxInfo boxinfo)
 {
     if (tick.sec % 5 != 0) return new Order();
     if (buyids.Count > 0)
         CancelOrders(true);
     else
         return new BuyLimit(Symbol, MinSize, 1);
     return new Order();
 }
Пример #11
0
 /// <summary>
 /// Create a box-info instance from an existing BarList
 /// </summary>
 /// <param name="bl">The barlist.</param>
 /// <returns>a BoxInfo</returns>
 public static BoxInfo FromBarList(BarList bl)
 {
     BoxInfo bi = new BoxInfo();
     if (!bl.HasBar()) return bi;
     bi.High = BarMath.HH(bl);
     bi.Low = BarMath.LL(bl);
     bi.Open = bl[0].Open;
     return bi;
 }
Пример #12
0
        public static decimal[] CORange(BarList chart)
        {
            List <decimal> l = new List <decimal>();

            foreach (Bar b in chart)
            {
                l.Add(b.Close - b.Open);
            }
            return(l.ToArray());
        }
Пример #13
0
        public static int[] Volumes(BarList chart)
        {
            List <int> l = new List <int>();

            foreach (Bar b in chart)
            {
                l.Add(b.Volume);
            }
            return(l.ToArray());
        }
Пример #14
0
        public static decimal[] Highs(BarList chart)
        {
            List <decimal> l = new List <decimal>();

            foreach (Bar b in chart)
            {
                l.Add(b.High);
            }
            return(l.ToArray());
        }
Пример #15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Chart"/> class.
 /// </summary>
 /// <param name="b">The barlist.</param>
 /// <param name="allowtype">if set to <c>true</c> [allowtype] will allow typing/changing of new symbols on the chart window.</param>
 public Chart(BarList b, bool allowtype)
 {
     InitializeComponent();
     bl          = b;
     Symbol      = b.Symbol;
     Paint      += new PaintEventHandler(Chart_Paint);
     MouseWheel += new MouseEventHandler(Chart_MouseUp);
     if (allowtype)
     {
         this.KeyUp += new KeyEventHandler(Chart_KeyUp);
     }
 }
Пример #16
0
        /// <summary>
        /// Build a barlist using an EPF file as the source
        /// </summary>
        /// <param name="filename">The filename.</param>
        /// <returns></returns>
        public static BarList FromEPF(string filename)
        {
            System.IO.StreamReader sr = new System.IO.StreamReader(filename);
            Stock   s = eSigTick.InitEpf(sr);
            BarList b = new BarList(BarInterval.FiveMin, s.Symbol);

            while (!sr.EndOfStream)
            {
                b.AddTick(eSigTick.FromStream(s.Symbol, sr));
            }
            return(b);
        }
Пример #17
0
        /// <summary>
        /// Build a barlist using an IDX (index) file as a source.
        /// </summary>
        /// <param name="filename">The filename.</param>
        /// <returns></returns>
        public static BarList FromIDX(string filename)
        {
            System.IO.StreamReader sr = new System.IO.StreamReader(filename);
            Index   i = Index.Deserialize(sr.ReadLine());
            BarList b = new BarList(BarInterval.FiveMin, i.Name);

            b.AddTick(i.ToTick());
            while (!sr.EndOfStream)
            {
                b.AddTick(Index.Deserialize(sr.ReadLine()).ToTick());
            }
            return(b);
        }
Пример #18
0
        /// <summary>
        /// Create a box-info instance from an existing BarList
        /// </summary>
        /// <param name="bl">The barlist.</param>
        /// <returns>a BoxInfo</returns>
        public static BoxInfo FromBarList(BarList bl)
        {
            BoxInfo bi = new BoxInfo();

            if (!bl.HasBar())
            {
                return(bi);
            }
            bi.High = BarMath.HH(bl);
            bi.Low  = BarMath.LL(bl);
            bi.Open = bl[0].Open;
            return(bi);
        }
Пример #19
0
 public bool newBar(BarList bl)
 {
     if (!bl.isValid) return false;
     Bar c = bl.RecentBar;
     if (!c.isValid) return false;
     decimal avgvol = AvgVol(bl);
     decimal moverequired = c.Open * _percent;
     bool voltest = (c.Volume - avgvol) > (avgvol * _bigvolper);
     isBigVolume = (ZeroAvgVolIsBig && voltest) || (!ZeroAvgVolIsBig && (avgvol != 0) && voltest);
     isBladeDOWN = ((c.Open - c.Close) > moverequired);
     isBladeUP = ((c.Close-c.Open) > moverequired);
     pctChange = c.Close / c.Open - 1;
     return true;
 }
Пример #20
0
        /// <summary>
        /// The lowest low for the barlist, considering so many bars back.
        /// </summary>
        /// <param name="b">The barlist.</param>
        /// <param name="barsback">The barsback to consider.</param>
        /// <returns></returns>
        public static decimal LL(BarList b, int barsback)
        { // gets lowest low
            if (barsback > b.Count)
            {
                barsback = b.Count;
            }
            decimal ll = decimal.MaxValue;

            for (int i = b.Last; i > (b.Count - barsback); i--)
            {
                ll = (b.Get(i).Low < ll) ? b.Get(i).Low : ll;
            }
            return(ll);
        }
Пример #21
0
        /// <summary>
        /// Returns the highest-high of the barlist, for so many bars back.
        /// </summary>
        /// <param name="b">The barlist.</param>
        /// <param name="barsback">The barsback to consider.</param>
        /// <returns></returns>
        public static decimal HH(BarList b, int barsback)
        {// gets highest high
            if (barsback > b.Count)
            {
                barsback = b.Count;
            }
            decimal hh = decimal.MinValue;

            for (int i = b.Last; i > (b.Count - barsback); i--)
            {
                hh = (b.Get(i).High > hh) ? b.Get(i).High : hh;
            }
            return(hh);
        }
Пример #22
0
        public static BarList[] FetchCharts(string[] symbols)
        {
            List <BarList> l = new List <BarList>();

            foreach (string sym in symbols)
            {
                BarList bl = new BarList(BarInterval.Day, sym);
                if (bl.DayFromGoogle())
                {
                    l.Add(bl);
                }
            }
            return(l.ToArray());
        }
Пример #23
0
        public static decimal[] TrueRange(BarList chart)
        {
            List <decimal> l = new List <decimal>();

            for (int i = chart.Last; i > 0; i--)
            {
                Bar     t   = chart[i];
                Bar     p   = chart[i - 1];
                decimal max = t.High > p.Close ? t.High : p.Close;
                decimal min = t.Low < p.Close ? t.Low : p.Close;
                l.Add(max - min);
            }
            return(l.ToArray());
        }
Пример #24
0
        protected override int Read(Tick tick, BarList bl,BoxInfo bi)
        {
            if (tick.isTrade)
            {
                sum += tick.trade;
                ticks++;
                MA = sum/ticks;

                if (((tick.time - starttime) % secperint) == 0) starttime = tick.time;
                if (starttime==0) return 0;

                bool pricecross = (((PosSize > 0) && (tick.trade < MA)) || ((PosSize < 0) && (tick.trade > MA)));
                return  (pricecross) ? Norm2Min(Flat*exitpercent) : 0;
            }
            return 0;
           
        }
Пример #25
0
        public void Basics()
        {
            const string sym = "TST";
            const int d = 20080509;
            const int t = 935;
            const string x = "NYSE";
            Tick[] ticklist = new Tick[] { 
                Tick.NewTrade(sym,d,t,0,10,100,x),
                Tick.NewTrade(sym,d,t+1,0,10,100,x),
                Tick.NewTrade(sym,d,t+2,0,10,100,x),
                Tick.NewTrade(sym,d,t+3,0,10,100,x),
                Tick.NewTrade(sym,d,t+4,0,15,100,x), // blade up
                Tick.NewTrade(sym,d,t+5,0,16,100,x), // new bar (blades reset)
                Tick.NewTrade(sym,d,t+6,0,16,100,x),
                Tick.NewTrade(sym,d,t+7,0,10,100,x), // blade down
                Tick.NewTrade(sym,d,t+7,10,10,100,x), // still a blade down (same bar)
                Tick.NewTrade(sym,d,t+8,0,15,100,x), 
                Tick.NewTrade(sym,d,t+15,0,15,800,x), // volume spike
                Tick.NewTrade(sym,d,t+20,0,15,100,x), 
                Tick.NewTrade(sym,d,t+25,0,15,100,x), 
            };

            BarList bl = new BarList(BarInterval.FiveMin,sym);
            Blade b = new Blade();
            Assert.That(b.BladePercentage != 0);
            b = new Blade(.2m); // 20 percent move is a blade
            int up=0,down=0,newbar=0,bigvol=0;

            foreach (Tick k in ticklist)
            {
                bl.AddTick(k);
                b.newBar(bl);
                if (bl.NewBar) newbar++;
                if (b.isBladeUP) up++;
                if (b.isBladeDOWN) down++;
                if (b.isBigVolume) bigvol++;
            }

            Assert.That(up == 1,up.ToString());
            Assert.That(down == 2,down.ToString());
            Assert.That(newbar == 5,newbar.ToString());
            Assert.That(bigvol == 1,bigvol.ToString());

        }
Пример #26
0
        /// <summary>
        /// Create a barlist from a succession of bar records provided as comma-delimited OHLC+volume data.
        /// </summary>
        /// <param name="symbol">The symbol.</param>
        /// <param name="file">The file containing the CSV records.</param>
        /// <returns></returns>
        public static BarList FromCSV(string symbol, string file)
        {
            BarList b = new BarList(BarInterval.Day, symbol);

            string[] line = file.Split(Environment.NewLine.ToCharArray());
            for (int i = line.Length - 1; i > 0; i--)
            {
                Bar mybar = null;
                if (line[i] != "")
                {
                    mybar = Bar.FromCSV(line[i]);
                }
                if (mybar != null)
                {
                    b.daylist.Add(mybar);
                }
            }
            return(b);
        }
Пример #27
0
        const decimal s = -.11m; // stop loss
        
        // here are the trading rules that implement our strategy's intention
        protected override int Read(Tick tick, BarList bl,BoxInfo bi)
        {
            // indicator setup
            bars = bl;
            if (!bl.Has(2)) return 0; // must have at least one one bar

            // asymmetry tests
            if (((h - o) > a) && ((o - l) > a)) { Shutdown("Not enough Asymetry to trade."); return 0; }
            if ((h - l) < r) return 0; // must have the range
            if (((h-o)<=a) && ((h-tick.trade)>e)) return MaxSize;
            if (((o-l)<=a) && ((tick.trade-l)>e)) return MaxSize*-1;

            // profit and loss tests
            decimal PL = BoxMath.OpenPT(tick.trade, AvgPrice, PosSize);
            if (PL > p) return Flat;
            if (PL < s) return Flat;

            return 0;
        }
Пример #28
0
        protected override int Read(Tick t, BarList barlist, BoxInfo bi)
        {
            this.tick = new Tick(t); // save tick to member for child classes
            this.bl   = barlist;     // save bars for same purpose
            _boxinfo  = bi;

            int adjust = 0;

            if (newTrade())
            {
                getStop();
            }
            else if (PosSize != 0) // if we have entry price, check exits
            {
                if (!IgnoreTick())
                {
                    checkMoveStop();
                }
                if (!IgnoreTick() && this.Exit())
                {
                    adjust = PosSize * -1;
                }
                else if (this.hitProfit())
                {
                    adjust = (PosSize > 0) ? ProfitSize : ProfitSize * -1;
                }
                else if (this.hitStop())
                {
                    adjust = PosSize * -1;
                }
            }
            else if (IgnoreTick())
            {
                adjust = 0;
            }
            else if (this.Enter()) // if haven't entered, check entry criteria
            {
                adjust = EntrySize * (Side ? 1 : -1);
            }
            return(adjust);
        }
Пример #29
0
        public void QuoteOnlyTest()
        {
            Tick[] timesales = new Tick[] {
                Tick.NewBid("TST",100m,100),
                Tick.NewAsk("TST",100.1m,200),
            };

            Blade b = new Blade();
            BarList bl = new BarList(BarInterval.FiveMin,"TST");

            foreach (Tick k in timesales)
            {
                bl.newTick(k);
                b.newBar(bl);
            }

            // average volume should be zero bc
            // with only quotes we should have no bars to process
            Assert.That(b.AvgVol(bl) == 0, b.AvgVol(bl).ToString());
            Assert.That(!bl.Has(1), bl.ToString());
        }
Пример #30
0
 /// <summary>
 /// Lowest low for the entire barlist.
 /// </summary>
 /// <param name="b">The barlist.</param>
 /// <returns></returns>
 public static decimal LL(BarList b)
 {
     return(LL(b, b.Count));
 }
Пример #31
0
 protected override int Read(Tick tick, BarList bl, BoxInfo boxinfo)
 {
     // go short off first trade
     if (tick.isTrade && (PosSize == 0)) return MinSize;
     // cover at the next opportunity
     else if (tick.isTrade && (PosSize != 0))
     {
         Shutdown("All done for today");
         return Flat;
     }
     return 0;
 }
Пример #32
0
 /// <summary>
 /// Returns the highest high for the entire barlist.
 /// </summary>
 /// <param name="b">The b.</param>
 /// <returns></returns>
 public static decimal HH(BarList b)
 {
     return(HH(b, b.Count));
 }
Пример #33
0
            protected override Order ReadOrder(Tick tick, BarList bl, BoxInfo boxinfo)
            {
                Order o = new Order();

                if (orders == 0)
                {
                    o = new LimitOrder(s, true, 200, 10);
                }
                if (orders==1)
                    CancelOrders(true);
                if (o.isValid)
                    orders++;
                return o;
            }
Пример #34
0
 /// <summary>
 /// Build a barlist using an EPF file as the source
 /// </summary>
 /// <param name="filename">The filename.</param>
 /// <returns></returns>
 public static BarList FromEPF(string filename)
 {
     System.IO.StreamReader sr = new System.IO.StreamReader(filename);
     Stock s = eSigTick.InitEpf(sr);
     BarList b = new BarList(BarInterval.FiveMin, s.Symbol);
     while (!sr.EndOfStream)
         b.AddTick(eSigTick.FromStream(s.Symbol,sr));
     return b;
 }
Пример #35
0
 protected override int  Read(Tick tick, BarList bl, BoxInfo boxinfo)
 {
     D("entering");
     return MinSize;
 }
Пример #36
0
        void kadinamain_KadTick(Tick t)
        {
            if ((t.sym == "") || (t.sym!=stock.Symbol)) return;
            // get stats prior to execution
            decimal cpl = broker.GetClosedPL(t.sym);
            decimal cpt = broker.GetClosedPT(t.sym);
            int x = broker.Execute(t);
            if (x != 0) // mark tick/row if an execution happened
                xrows.Add(dt.Rows.Count - 1);

            nowtime = t.time.ToString() + ":" + t.sec.ToString();

            if (bl == null) 
                bl = new BarList(BarInterval.FiveMin, t.sym);
            bl.AddTick(t);
            Order o = new Order();
            Position mypos = broker.GetOpenPosition(t.sym);
            if (mybox != null)
            {
                o = mybox.Trade(t, bl, mypos, BoxInfo.FromBarList(bl));
                mybox_IndicatorUpdate(mybox.Indicators);
            }

            if (o.isValid) // mark tick/row if an order happened
                orows.Add(dt.Rows.Count - 1);
            broker.sendOrder(o);
            string flags = "";
            flags += o.isValid ? "O" : "";
            flags += x > 0 ? "X" : "";
            
            // tick grid
            NewTRow(new object[] { nowtime, t.trade, t.size, t.bid, t.ask, t.bs, t.os, flags });
            // position grid
            if (x != 0)
            {
                // get difference between stats pre and stats post
                cpl = broker.GetClosedPL(t.sym) - cpl;
                cpt = broker.GetClosedPT(t.sym) - cpt;
                ptab.Rows.Add(nowtime, (mypos.Flat ? "FLAT" : (mypos.Side ? "LONG" : "SHORT")), mypos.Size, mypos.AvgPrice, cpl.ToString("C2"),cpt.ToString("N1"));
            }
        }
Пример #37
0
        public int Test(List<FileInfo> tf) 
        {
            show("Starting run "+name+" containing "+ tf.Count + " symbols."+Environment.NewLine);
            int totfills = 0;
            int totalticks = approxticks(tf);

            for (int i = 1; i <= tf.Count; i++) // loop through the list
            {
                FileInfo f = tf[i-1];
                Match m = Regex.Match(f.Name, "([0-9]+)", RegexOptions.IgnoreCase);
                int date = Convert.ToInt32(m.Result("$1"));
                LoadIndexFiles(date);
                TickFile(f.Name); // set current file
                if (f.Length == 0) continue; // ignore if tick file is empty
                show(Environment.NewLine);
                show("Symbol " + this.symbol + " (" + i + " of " + tf.Count + ") ");

                // reset per-symbol statistics
                if (mybox!=null) mybox.Reset();
                bl = new BarList((BarInterval)bint, symbol);
                int fills = 0;
                tick = new eSigTick(); // reset our tick
                int itime = 0;
                BoxInfo bi = new BoxInfo();
                

                while (this.getTick() && tick.hasTick)
                { // process the ticks
                    line++;
                    if ((line % 5000) == 0) show(".");
                    if (((itime==0) || (itime!=tick.time)))
                    {
                        // load all the indicies for this time
                        List<Index> itix = FetchIdx(tick.time);
                        itime = tick.time;
                        // send them to the box (before we send the tix)
                        for (int id = 0; id < itix.Count; id++)
                            mybox.NewIndex(itix[id]);
                    }

                    if ((this.exfilter != "") &&
                        ((!tick.isTrade && (!tick.be.Contains(exfilter) || !tick.oe.Contains(exfilter))) ||
                         (tick.isTrade && tick.ex.Contains(exfilter)))) continue;

                    if ((bi.Open == 0) && tick.isTrade) 
                        bi.Open = tick.trade;

                    if (tick.trade > bi.High) bi.High = tick.trade;
                    if (tick.trade < bi.Low) bi.Low = tick.trade;
                    bl.AddTick(tick); // save our tick to a bar

                    if (bl.Has(2) && bl.Get(bl.Last-1).DayEnd)
                    { // we hit a new day in the same file, reset day stuff and set our DayEndTime
                        bl.Reset();
                        bl.AddTick(tick); // put our tick back

                        if (mybox!=null) mybox.Reset();
                        SetDayClose(); // this has to be run after mybox.Reset!!!
                    }


                    // execute any pending orders on this tick
                    if (mybroker.GetOrderList().Count>0) fills += mybroker.Execute(tick); 
                    // trade box on this tick, if he generates any orders then send them
                    if (mybox != null)
                    {
                        mybroker.sendOrder(
                            mybox.Trade(tick, bl, mybroker.GetOpenPosition(this.symbol), bi));
                        // quit early if box shuts itself off and no pending orders
                        if (mybox.Off && (mybroker.GetOrderList().Count == 0)) break;
                    }


                    if (this.delay != 0)
                    {
                        System.Threading.Thread.Sleep(this.delay);
                        System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Lowest;
                    }
                    this.ReportProgress((int)((100*line) / totalticks));
                }
                show(fills+" executions.");
                totfills += fills;
                this.cf.Close();
            }
            show(Environment.NewLine);
            show(name+" complete: "+tf.Count+" symbols, "+ totfills + " executions."+Environment.NewLine);
            return totfills;
        }
Пример #38
0
        /// <summary>
        /// Trades specified tick.  This method will call an inherited overridden member Read if QuickOrder is true or ReadOrder if QuickOrder is false.
        /// </summary>
        /// <param name="tick">The tick.</param>
        /// <param name="bl">The barlist.</param>
        /// <param name="pos">The current position in the stock or instrument.</param>
        /// <param name="bi">Other box information.</param>
        /// <returns></returns>
        public Order Trade(Tick tick, BarList bl, Position pos, BoxInfo bi)
        {
            Order o = new Order();

            if (Symbol == null)
            {
                if (tick.sym != "")
                {
                    symbol = tick.sym;
                }
                else
                {
                    throw new Exception("No symbol specified");
                }
                _pos = new Position(tick.sym);
            }
            if (!pos.isValid)
            {
                throw new Exception("Invalid Position Provided to Box" + pos.ToString());
            }
            if (tick.sym != Symbol)
            {
                return(o);
            }
            time = tick.time;
            date = tick.date;
            sec  = tick.sec;


            if ((Time < DayStart) || (Time > DayEnd))
            {
                return(o);                                    // is market open?
            }
            if (Off)
            {
                return(o);     // don't trade if shutdown
            }
            if (TradeCaps && pos.Flat && ((this.turns >= MAXTRADES) || (this.adjusts >= MAXADJUSTS)))
            {
                this.Shutdown("Trade limit reached.");
                return(o);
            }
            _pos = pos;

            if (QuickOrder) // user providing only size adjustment
            {
                // get our adjustment
                int adjust = this.Read(tick, bl, bi);

                // convert adjustment to an order
                o = this.Adjust(adjust);
            }
            else // user providing a complete order, so get it
            {
                o = ReadOrder(tick, bl, bi);
            }

            if (!OrdersAllowed) // if we're not allowed, mark order as invalid
            {
                o = new Order();
            }

            //flat us at the close
            if (!_sentshut && (Time >= (DayEnd - DayEndBuff)))
            {
                o      = this.Adjust(Flat);
                o.time = Time;
                o.date = Date;
                this.Shutdown("end-of-day");
                _sentshut = true;
            }
            if (o.isValid)
            {
                // if it's a valid order it counts as an adjustment
                adjusts++;
                // if we're going to flat from non-flat, this is a "trade"
                if ((Math.Abs(PosSize + o.SignedSize) == 0) && (PosSize != 0))
                {
                    turns++;
                }

                // final prep for good orders
                _expectedpossize += o.SignedSize;
                o.time            = Time;
                o.date            = Date;
            }

            if (o.isValid)
            {
                this.D("Sent order: " + o);
            }
            return(o); // send our order
        }
Пример #39
0
 /// <summary>
 /// Called everytime a new tick is received by the box, if QuickOrder is false.  Reads from the user a position adjustment as an order.
 /// </summary>
 /// <param name="tick">The current tick.</param>
 /// <param name="bl">The current barlist.</param>
 /// <param name="boxinfo">The boxinfo.</param>
 /// <returns>The number of shares to adjust the position up or down.</returns>        protected virtual Order ReadOrder(Tick tick, BarList bl,BoxInfo boxinfo) { D("No ReadOrder function provided.");  return new Order(); }
 protected virtual Order ReadOrder(Tick tick, BarList bl, BoxInfo boxinfo)
 {
     D("No ReadOrder function provided."); return(new Order());
 }
Пример #40
0
        public void BollingerBarlisttest()
        {

            string symbol = "TST";


            BarList bl = new BarList(BarInterval.Minute, symbol);
            Bollinger bbb = new Bollinger(2, BarInterval.Minute, 10);
            foreach (Tick t in ticklist)
            {
                bl.AddTick(t);
                bbb.newBar(bl);
            }

            Assert.That(bbb.Mean == 3, bbb.Mean.ToString());
            Assert.That(bbb.Devavg == 2, bbb.Devavg.ToString());
            Assert.That(bbb.Sd == 1.4142135623730950488016887242097, bbb.Sd.ToString());
            Assert.That(bbb.Upperband == 5.8284271247462M, bbb.Upperband.ToString());
        }
Пример #41
0
 public Chart(BarList b) : this(b, false) { }
Пример #42
0
 public void NewBarList(int MinInterval)
 {
     bl = new BarList((BarInterval)MinInterval);
 }
Пример #43
0
        /// <summary>
        /// Trades specified tick.  This method will call an inherited overridden member Read if QuickOrder is true or ReadOrder if QuickOrder is false.
        /// </summary>
        /// <param name="tick">The tick.</param>
        /// <param name="bl">The barlist.</param>
        /// <param name="pos">The current position in the stock or instrument.</param>
        /// <param name="bi">Other box information.</param>
        /// <returns></returns>
        public Order Trade(Tick tick,BarList bl, Position pos,BoxInfo bi)
        {
            Order o = new Order();
            if (Symbol == null)
            {
                if (tick.sym != "") symbol = tick.sym;
                else throw new Exception("No symbol specified");
                _pos = new Position(tick.sym);
            }
            if (!pos.isValid) throw new Exception("Invalid Position Provided to Box" + pos.ToString());
            if (tick.sym != Symbol) return o;
            time = tick.time;
            date = tick.date;
            sec = tick.sec;

           
            if ((Time < DayStart) || (Time>DayEnd)) return o; // is market open?
            if (Off) return o; // don't trade if shutdown
            if (TradeCaps &&  pos.Flat && ((this.turns >= MAXTRADES) || (this.adjusts >= MAXADJUSTS)))
            {
                this.Shutdown("Trade limit reached.");
                return o;
            }
            _pos = pos;

            if (QuickOrder) // user providing only size adjustment
            {
                // get our adjustment
                int adjust = this.Read(tick, bl,bi);  

                // convert adjustment to an order
                o = this.Adjust(adjust); 
            }
            else // user providing a complete order, so get it
            {
                o = ReadOrder(tick, bl,bi);
            }

            if (!OrdersAllowed) // if we're not allowed, mark order as invalid
                o = new Order();

            //flat us at the close
            if (!_sentshut && (Time >= (DayEnd - DayEndBuff)))
            {
                o = this.Adjust(Flat);
                o.time = Time;
                o.date = Date;
                this.Shutdown("end-of-day");
                _sentshut = true;
            }
            if (o.isValid)
            {
                // if it's a valid order it counts as an adjustment
                adjusts++;
                // if we're going to flat from non-flat, this is a "trade"
                if ((Math.Abs(PosSize + o.SignedSize) == 0) && (PosSize != 0)) 
                    turns++;

                // final prep for good orders
                _expectedpossize += o.SignedSize;
                o.time = Time;
                o.date = Date;
            }
            
            if (o.isValid) this.D("Sent order: " + o);
            return o; // send our order
        }
Пример #44
0
 /// <summary>
 /// Called everytime a new tick is received by the box, if QuickOrder is false.  Reads from the user a position adjustment as an order.
 /// </summary>
 /// <param name="tick">The current tick.</param>
 /// <param name="bl">The current barlist.</param>
 /// <param name="boxinfo">The boxinfo.</param>
 /// <returns>The number of shares to adjust the position up or down.</returns>        protected virtual Order ReadOrder(Tick tick, BarList bl,BoxInfo boxinfo) { D("No ReadOrder function provided.");  return new Order(); }
 protected virtual Order ReadOrder(Tick tick, BarList bl, BoxInfo boxinfo) { D("No ReadOrder function provided."); return new Order(); }
Пример #45
0
 /// <summary>
 /// Called everytime a new tick is received by the box, if QuickOrder is true (default).  Reads from the user a position adjustment as an integer.
 /// </summary>
 /// <param name="tick">The current tick.</param>
 /// <param name="bl">The current barlist.</param>
 /// <param name="boxinfo">The boxinfo.</param>
 /// <returns>The number of shares to adjust the position up or down.</returns>
 protected virtual int Read(Tick tick, BarList bl, BoxInfo boxinfo)
 {
     D("No Read function provided"); return(0);
 }
Пример #46
0
 /// <summary>
 /// Build a barlist using an IDX (index) file as a source.
 /// </summary>
 /// <param name="filename">The filename.</param>
 /// <returns></returns>
 public static BarList FromIDX(string filename)
 {
     System.IO.StreamReader sr = new System.IO.StreamReader(filename);
     Index i = Index.Deserialize(sr.ReadLine());
     BarList b = new BarList(BarInterval.FiveMin, i.Name);
     b.AddTick(i.ToTick());
     while (!sr.EndOfStream)
         b.AddTick(Index.Deserialize(sr.ReadLine()).ToTick());
     return b;
 }
Пример #47
0
 public Chart(BarList b) : this(b, false)
 {
 }
Пример #48
0
        protected override int Read(Tick t,BarList barlist,BoxInfo bi)
        {
            this.tick = new Tick(t); // save tick to member for child classes
            this.bl = barlist; // save bars for same purpose
            _boxinfo = bi;

            int adjust = 0;
            if (newTrade()) getStop(); 
            else if (PosSize != 0) // if we have entry price, check exits
            {
                if (!IgnoreTick()) checkMoveStop();
                if (!IgnoreTick() && this.Exit()) adjust = PosSize * -1;
                else if (this.hitProfit()) adjust = (PosSize > 0) ? ProfitSize : ProfitSize * -1;
                else if (this.hitStop()) adjust = PosSize * -1;
            }
            else if (IgnoreTick()) adjust = 0;
            else if (this.Enter()) // if haven't entered, check entry criteria
                adjust = EntrySize * (Side ? 1 : -1);
            return adjust;
        }
Пример #49
0
        public void BollingerBarlisttestlookbacks()
        {
            string symbol = "TST";

            BarList bl = new BarList(BarInterval.Minute, symbol);
            Bollinger bbb = new Bollinger(2, BarInterval.Minute, 4);
            foreach (Tick t in ticklist)
            {
                bl.AddTick(t);
                bbb.newBar(bl);
            }

            Assert.That(bbb.Mean == 3.5M, bbb.Mean.ToString());
            Assert.That(bbb.Devavg == 1.25M, bbb.Devavg.ToString());
            Assert.That(bbb.Sd == 1.1180339887498948482045868343656, bbb.Sd.ToString());
            Assert.That(bbb.Upperband == 5.73606797749978M, bbb.Upperband.ToString());
            Assert.That(bbb.Lowerband == 1.26393202250022M, bbb.Lowerband.ToString());
        }
Пример #50
0
        /// <summary>
        /// Create a barlist from a succession of bar records provided as comma-delimited OHLC+volume data.
        /// </summary>
        /// <param name="symbol">The symbol.</param>
        /// <param name="file">The file containing the CSV records.</param>
        /// <returns></returns>
        public static BarList FromCSV(string symbol, string file)
        {
            BarList b = new BarList(BarInterval.Day, symbol);
            string[] line = file.Split(Environment.NewLine.ToCharArray());
            for (int i = line.Length - 1; i > 0; i--)
            {
                Bar mybar = null;
                if (line[i] != "") mybar = Bar.FromCSV(line[i]);
                if (mybar != null) b.daylist.Add(mybar);
            }
            return b;

        }