protected override List <ResponseModel> getmodels()
        {
            List <ResponseModel> mods = new List <ResponseModel>();

            if (!isValid)
            {
                debug("Can't add models when response is not loaded.");
                symbols2add = new string[0];
                return(mods);
            }
            var indcount = mygvi.Count;

            foreach (var sym in symbols2add)
            {
                // get index
                var idx = sym2modidx.getindex(sym);
                // skip if already have it
                if (idx >= 0)
                {
                    continue;
                }
                dynamic mod = new ResponseModel(indcount);
                mod.symbol        = sym;
                mod.responseowner = ResponseName;
                mods.Add(mod);
                idx = sym2modidx.addindex(sym, models.Count);
                sym2lastupdatetime.addindex(sym, -1);
            }
            return(mods);
        }
        void GotNewBar(string symbol, int interval)
        {
            // get current barlist for this symbol+interval
            BarList bl = track_barlists[symbol, interval];
            // get index for symbol
            int idx = track_symbols.getindex(symbol);

            // check for first cross on first interval
            if (interval == (int)BarInterval.Minute)
            {
                //
                D("(int)BarInterval.Minute interval=" + interval);
                return;
            }
            // check second cross
            if (interval == (int)BarInterval.FiveMin)
            {
                //
                D("(int)BarInterval.FiveMin interval=" + interval);
                return;
            }
            D("else.. interval=" + interval);
            return;

            // // nice way to notify of current tracker values
            // sendindicators(gt.GetIndicatorValues(idx, gens()));
        }
        public void Basics()
        {
            // reset count
            newtxt = 0;
            // track something
            GenericTracker <object> gt = new GenericTracker <object>();

            // count new items
            gt.NewTxt += new TextIdxDelegate(gt_NewTxt);
            // get some symbols
            string[] syms = new string[] { "IBM", "LVS", "IBM", "WAG", "GOOG" };
            // add them
            foreach (string sym in syms)
            {
                gt.addindex(sym, sym == "IBM" ? null : new object());
            }
            // ensure we have them
            Assert.AreEqual(4, newtxt);
            Assert.AreNotEqual(gt.Count, syms.Length);
            // test fetching by label
            Assert.IsNull(gt["IBM"]);
            Assert.IsNotNull(gt["GOOG"]);
            Assert.AreEqual(0, gt.getindex("IBM"));
            // get label from index
            Assert.AreEqual("GOOG", gt.getlabel(3));
        }
        /// <summary>
        /// Called whenever we got a trade signal
        /// </summary>
        /// <param name="f"></param>
        public override void GotFill(Trade fill)
        {
            // make sure every fill is tracked against a position
            int sizebefore = _pt[fill.symbol].Size;

            _pt.Adjust(fill);
            bool isclosing = (sizebefore) * fill.xsize < 0;

            if (isclosing)
            {
                decimal pl = Calc.Sum(Calc.AbsoluteReturn(_pt));
                TotalProfit = pl;
            }
            // get index for this symbol
            int idx = _wait.getindex(fill.symbol);

            // ignore unknown symbols
            if (idx < 0)
            {
                return;
            }
            // stop waiting
            _wait[fill.symbol] = false;
#if DEBUG
            string line = FormatLog(_pt[0].ToString());
            debugWriter.WriteLine(line);
#endif
        }
        /// <summary>
        /// This function will be delegated in "Reset" method
        /// and will be called whenever the system got a new bar
        /// The stratege should be contained in this method
        /// </summary>
        /// <param name="symbol"></param>
        /// <param name="interval"></param>
        void blt_GotNewBar(string symbol, int interval)
        {
            BarList myBars = _blt[symbol, interval];

            // If we only get one bar, exit
            if (myBars.Count <= 1)
            {
                return;
            }
            // make sure the lastBar is full
            _lastBar = myBars[myBars.Count - 2];
            // Update lastBars
            if (_lastBars.getindex(symbol) < 0)
            {
                _lastBars.addindex(symbol);
            }
            _lastBars[symbol] = _lastBar;
            // Update indicators
            ComputeSignal();
            string[] indicators = GetDisplayIndicators();
            sendindicators(indicators);
            // Buy or sell
            // Strategy based on computed ATR indicator
            //DoStrategy(symbol, signal);
            DoStrategy();
        }
Esempio n. 6
0
        void GotNewBar(string symbol, int interval)
        {
            // get current barlist for this symbol+interval
            BarList bl = blt[symbol, interval];
            // get index for symbol
            int idx = PRIMARY.getindex(symbol);

            // check for first cross on first interval
            if (interval == (int)BarInterval.Minute)
            {
                // update the cross state
                indicatorcross1[symbol] = bl.RecentBar.Close > Calc.Avg(bl.Close());
            }
            // check second cross
            if (interval == (int)BarInterval.FiveMin)
            {
                // update the cross state
                indicatorcross2[symbol] = bl.RecentBar.Close > Calc.Avg(bl.Close());
            }
            // update first1then2
            if (first1then2ok[symbol] && indicatorcross2[symbol] && !indicatorcross1[symbol])
            {
                first1then2ok[symbol] = false;
            }
            // send order if everything looks good
            if (first1then2ok[symbol] && indicatorcross2[symbol] && indicatorcross1[symbol])
            {
                sendorder(new BuyMarket(symbol, 100));
            }
            // notify of current tracker values
            sendindicators(gt.GetIndicatorValues(idx, gens()));
        }
Esempio n. 7
0
        internal static string gethelpercode(string fname, GenericTracker <List <Token> > functionname2body)
        {
            var fidx = functionname2body.getindex(fname);
            var stublessimplementation = getstublessfunction(fidx, functionname2body);
            var funccode = gettokencode(stublessimplementation.ToArray());

            return(funccode);
        }
        /// <summary>
        /// Called whenever we got a tick signal
        /// </summary>
        /// <param name="k"></param>
        public override void GotTick(Tick k)
        {
            // Sync symbols
            if (_symbols.getindex(k.symbol) < 0)
            {
                _symbols.addindex(k.symbol, k.symbol);
            }

            SyncDateTime(k);

            // ensure response is active
            if (!isValid)
            {
                return;
            }

            // ensure we are tracking active status for this symbol
            int idx = _active.addindex(k.symbol, true);

            // if we're not active, quit
            if (!_active[idx])
            {
                return;
            }

            //// check for shutdown time
            //if (k.time > Shutdown)
            //{
            //    // if so, shutdown the system
            //    if (!_isShutDown)
            //    {
            //        shutdown();
            //    }
            //    // and quit
            //    return;
            //}
            //else
            //{
            //    // make sure the flag is on
            //    _isShutDown = false;
            //}
            // apply bar tracking to all ticks that enter
            _kt.newTick(k);
            _blt.newTick(k);

            // ignore anything that is not a trade
            if (!k.isTrade)
            {
                return;
            }
        }
Esempio n. 9
0
        public override void GotFill(Trade fill)
        {
            // make sure every fill is tracked against a position
            pt.Adjust(fill);
            // get index for this symbol
            int idx = _wait.getindex(fill.symbol);

            // ignore unknown symbols
            if (idx < 0)
            {
                return;
            }
            // stop waiting
            _wait[fill.symbol] = false;
            // chart fills
            sendchartlabel(fill.xprice, time, TradeImpl.ToChartLabel(fill), fill.side ? System.Drawing.Color.Green : System.Drawing.Color.Red);
        }
Esempio n. 10
0
 /// <summary>
 /// returns absolute return of all positions in order they are listed in position tracker
 /// both closed and open pl may be included
 /// </summary>
 /// <param name="pt"></param>
 /// <param name="marketprices"></param>
 /// <param name="countClosedPL"></param>
 /// <returns></returns>
 public static decimal[] AbsoluteReturn(PositionTracker pt, GenericTracker<decimal> marketprices, bool countClosedPL)
 {
     decimal[] aret = new decimal[pt.Count];
     bool countOpenPL = marketprices.Count >= pt.Count;
     for (int i = 0; i < pt.Count; i++)
     {
         // get position
         Position p = pt[i];
         // get index
         int idx = marketprices.getindex(p.Symbol);
         // see if we're doing open
         if (countOpenPL && (idx >= 0))
             aret[i] += Calc.OpenPL(marketprices[idx], p);
         if (countClosedPL)
             aret[i] += p.ClosedPL;
     }
     return aret;
 }
Esempio n. 11
0
        void newbar(string symbol, int interval)
        {
            // get tracker index for our symbol
            int idx = MA.getindex(symbol);
            // get some data
            BarList bl = blt[symbol, interval];

            // convert it to form that ta-lib understands
            double[] closes = Calc.Decimal2Double(bl.Close());
            // call your indicator
            double[] ma = new double[closes.Length];
            int      bi, oi;

            Core.Sma(0, closes.Length - 1, closes, LOOKBACK[idx], out bi, out oi, ma);
            // populate your tracker with most recent value
            Calc.TAPopulateGT(idx, oi, ref ma, MA);
            // display our indicators
            sendindicators(gt.GetIndicatorValues(idx, MA, LOOKBACK));
        }
Esempio n. 12
0
        public override void GotFill(TradeLink.API.Trade fill)
        {
            // keep track of position
            D(fill.symbol + " fill: " + fill.ToString());
            _pt.Adjust(fill);
            // ensure fill comes from this response
            int idx = _entrysignal.getindex(fill.symbol);

            if (idx < 0)
            {
                return;
            }
            // reset signals if we're flat (allows re-entry)
            if (_pt[fill.symbol].isFlat)
            {
                _entrysignal[fill.symbol] = false;
                _exitsignal[fill.symbol]  = false;
            }
        }
Esempio n. 13
0
        public void GotTick(Tick k)
        {
            // skip if disabled
            if (!isReady)
            {
                return;
            }
            // ensure tick is desired by this response
            var idx = sym2lastupdatetime.getindex(k.symbol);

            if (idx < 0)
            {
                return;
            }
            // update time
            _lastticktime = k.time;
            // pass tick
            response.GotTick(k);
        }
Esempio n. 14
0
        int getindex(string iname)
        {
            var idx = iname2validx.getindex(iname);

            // build index first time
            if (idx < 0)
            {
                var inds = getgvi().itemnames;
                for (int i = 0; i < inds.Count; i++)
                {
                    var tmpiname = inds[i];
                    if (tmpiname == iname)
                    {
                        idx = i;
                    }
                    iname2validx.addindex(tmpiname, i);
                }
            }
            return(idx);
        }
Esempio n. 15
0
        internal static Token[] gethelperconstants(Token[] ftoks, GenericTracker <Token[]> const2toks)
        {
            List <Token> usedconstants = new List <Token>();

            // keep track of what has been added
            bool[] constadded = new bool[const2toks.Count];

            // go through every function token
            foreach (var tok in ftoks)
            {
                // skip anything that is not a symbol
                if (!tok.isSymbol)
                {
                    continue;
                }
                // see if this token is a constant
                int idx = const2toks.getindex(tok.data);
                // it's not, so we don't need to declare it's implementation
                if (idx < 0)
                {
                    continue;
                }
                else if (constadded[idx]) // it's already been added
                {
                    continue;
                }
                else // otherwise we likely need to define it
                {
                    // define it
                    usedconstants.AddRange(const2toks[idx]);
                    // add new line
                    usedconstants.Add(new Token(tokentype.line));
                    // mark it as defined
                    constadded[idx] = true;
                }
            }

            // return all the likely helpers
            return(usedconstants.ToArray());
        }
Esempio n. 16
0
        void client_gotUnknownMessage(MessageTypes type, long source, long dest, long msgid, string request, ref string response)
        {
            if (type == MessageTypes.BARRESPONSE)
            {
                lastbarraw = response;
                var b         = BarImpl.Deserialize(response);
                var label     = b.Symbol + b.Interval.ToString() + b.CustomInterval.ToString();
                var symintidx = symintcount.getindex(label);
                if (symintidx < 0)
                {
                    symintidx = symintcount.addindex(label, new List <Bar>());
                    g.d("got new symbol/interval: " + b.Symbol + " " + b.Interval + b.CustomInterval + " bar:" + b.ToString());
                }

                symintcount[symintidx].Add(b);
                if (!recvsyms.Contains(b.Symbol))
                {
                    recvsyms.Add(b.Symbol);
                }
                recvbarcount++;
            }
            else if (type == MessageTypes.BARRESPONSE_FINAL)
            {
                var br = BarRequest.Deserialize(response);
                reccomplete++;
                g.d("completed: " + br.symbol + " " + br.Interval + " " + br.ID);
            }
            else
            {
                g.d("got unknown message: " + type + request + response);
            }
            var ok = mt.GotMessage(type, source, dest, msgid, request, ref response);

            if (!ok)
            {
                g.d("error processing: " + type + " request: " + request + " response: " + response);
            }
            msgok &= ok;
        }
Esempio n. 17
0
 public void Basics()
 {
     // reset count
     newtxt = 0;
     // track something
     GenericTracker<object> gt = new GenericTracker<object>();
     // count new items
     gt.NewTxt += new TextIdxDelegate(gt_NewTxt);
     // get some symbols
     string[] syms = new string[] { "IBM", "LVS", "IBM", "WAG", "GOOG" };
     // add them
     foreach (string sym in syms)
         gt.addindex(sym, sym == "IBM" ? null : new object());
     // ensure we have them
     Assert.AreEqual(4, newtxt);
     Assert.AreNotEqual(gt.Count, syms.Length);
     // test fetching by label
     Assert.IsNull(gt["IBM"]);
     Assert.IsNotNull(gt["GOOG"]);
     Assert.AreEqual(0, gt.getindex("IBM"));
     // get label from index
     Assert.AreEqual("GOOG", gt.getlabel(3));
 }
        /// <summary>
        /// Called whenever we got a trade signal
        /// </summary>
        /// <param name="f"></param>
        public override void GotFill(Trade fill)
        {
            // make sure every fill is tracked against a position
            int sizebefore = _pt[fill.symbol].Size;

            _pt.Adjust(fill);
            bool isclosing = (sizebefore) * fill.xsize < 0;

            if (isclosing)
            {
                decimal pl = Calc.Sum(Calc.AbsoluteReturn(_pt));
                _totalprofit = pl;
            }
            // get index for this symbol
            int idx = _wait.getindex(fill.symbol);

            // ignore unknown symbols
            if (idx < 0)
            {
                return;
            }
            // stop waiting
            _wait[fill.symbol] = false;
        }
Esempio n. 19
0
        protected override List <Quote> getmodels()
        {
            // add them
            var mods = new List <Quote>();

            foreach (var sym in symbols2add)
            {
                // skip if we already have the symbol
                var idx = symidx.getindex(sym);
                if (idx < 0)
                {
                    Quote q = new Quote();
                    q.symbol = sym;
                    mods.Add(q);
                    idx = symidx.addindex(sym, mods.Count - 1);
                    sym2lasttime.addindex(sym, -1);
                    debug(sym + " added quote.");
                }
            }



            return(mods);
        }
Esempio n. 20
0
 public static bool TAPopulateGT(string sym, int nb, ref int[] res, GenericTracker<int> gt) { int idx = gt.getindex(sym);  return TAPopulateGT(idx, nb, 0, ref res, gt); }
Esempio n. 21
0
        void blt_GotNewBar(string symbol, int interval)
        {
            int          idx = _active.getindex(symbol);
            BarList      myBarList = blt[symbol];
            Bar          curBar = myBarList.RecentBar;
            int          barCount = myBarList.Count;   int lastBar = barCount - 1;
            decimal      oneTick   = tickValue; //this is hard-coded for ES contracts
            tradeLog     curTrade  = new tradeLog();
            turtleSignal curSignal = new turtleSignal();

            //doing manual sizing here
            int units = manualTradeUnit;

            if (myBarList.Count < myParams.ATRLen)
            {
                D("Error: waiting for more bars. or you can request more history data"); return;
            }

            // calculate the SMA using closing prices for so many bars back
            //decimal SMA = MyCalc.Avg(Calc.EndSlice(blt[symbol].Close(), _barsback));
            //TODO: optimize this one calculation
            curSignal.ATR = MyCalc.AverageTrueRange(blt[symbol], myParams.ATRLen);
            if (curSignal.ATR < 0)
            {
                D("Error calc ATR"); return;
            }

            switch (myParams.TurtleSystem)
            {
            case SystemType.System_One:

                if (myTrades.Count == 0)    //essentially trade.Init
                {
                    lastTrade = 0;
                    entry     = 0;  exit = 0;
                    curTrade  = trade.Flat;
                    myTrades.Add(curTrade);
                    tradeProfitPoints = 0;
                    stop       = 0;
                    entryUnits = units;     //using this for now.
                }
                break;

                switch (myTrades[myTrades.Count - 1])
                {
                case trade.Init:
                {
                    lastTrade = 0;
                }

                case trade.Flat:

                    if ((curBar.High > longEntry && lastTrade == 1 && curBar.High < failSafeLongEntry) && skipConsecutiveTrades)
                    {
                        entry             = Math.Max(longEntry + oneTick, curBar.Low);
                        exit              = 0;
                        curTrade          = trade.SkipLong;
                        tradeProfitPoints = 0;
                        stop              = entry - ATRMultiplier * ATR;
                        entryUnits        = units;
                        lastTrade         = 0;
                    }
                    else if (((curBar.Low < shortEntry && lastTrade == 1 && curBar.Low > failSafeShortEntry)) && skipConsecutiveTrades)
                    {
                        entry             = Math.Min(shortEntry - oneTick, curBar.High);
                        exit              = 0;
                        curTrade          = trade.SkipShort;
                        tradeProfitPoints = 0;
                        stop              = entry + ATRMultiplier * ATR;
                        entryUnits        = units;
                        lastTrade         = 0;
                    }
                    else if (curBar.High > longEntry)
                    {
                        entry             = Math.Max(longEntry + oneTick, curBar.Low);
                        exit              = 0;
                        curTrade          = trade.GoLong;
                        tradeProfitPoints = 0;
                        stop              = entry - ATRMultiplier * ATR;
                        entryUnits        = units;
                        lastTrade         = 0;
                    }
                    else if (curBar.Low < shortEntry)
                    {
                        entry             = Math.Min(shortEntry - oneTick, curBar.High);
                        exit              = 0;
                        curTrade          = trade.GoShort;
                        tradeProfitPoints = 0;
                        stop              = entry + ATRMultiplier * ATR;
                        entryUnits        = units;
                        lastTrade         = 0;
                    }
                    else
                    {
                        entry             = 0;
                        exit              = 0;
                        curTrade          = trade.Flat;
                        tradeProfitPoints = 0;
                        stop              = -1.0m;
                        entryUnits        = entryUnits[1];
                        lastTrade         = lastTrade[1];
                    }

                case trade.GoLong:
                    entryUnits = entryUnits[1];
                    if (curBar.Low < longExit || curBar.Low < stop[1])
                    {
                        exit              = Math.Min(curBar.Open, Math.Max(longExit - oneTick, stop[1] - oneTick));
                        entry             = entry[1];
                        curTrade          = trade.Flat;
                        tradeProfitPoints = exit - entry[1];
                        stop              = -1m;
                        lastTrade         = tradeProfitPoints > 0 ? 1 : 0;
                    }
                    else
                    {
                        exit              = 0;
                        entry             = entry[1];
                        curTrade          = trade.GoLong;
                        tradeProfitPoints = 0;
                        stop              = stop[1];
                        lastTrade         = lastTrade[1];
                    }

                case trade.GoShort:
                    entryUnits = entryUnits[1];
                    if (curBar.High > shortExit || curBar.High > stop[1])
                    {
                        exit              = Math.Max(curBar.Open, Math.Min(shortExit + oneTick, stop[1] + oneTick));
                        entry             = entry[1];
                        curTrade          = trade.Flat;
                        tradeProfitPoints = entry[1] - exit;
                        stop              = -1m;
                        lastTrade         = tradeProfitPoints > ? 1 : 0;
                    }
                    else
                    {
                        exit              = 0;
                        entry             = entry[1];
                        curTrade          = trade.GoShort;
                        tradeProfitPoints = 0;
                        stop              = stop[1];
                        lastTrade         = lastTrade[1];
                    }

                case trade.SkipLong:
                    if (curBar.Low < longExit || curBar.Low < stop[1])
                    {
                        exit              = Math.Min(curBar.Open, Math.Max(longExit - oneTick, stop[1] - oneTick));
                        entry             = entry[1];
                        curTrade          = trade.Flat;
                        tradeProfitPoints = exit - entry[1];
                        stop              = -1m;
                        lastTrade         = 0;
                        entryUnits        = 0;
                    }
                    else if (curBar.High > failSafeLongEntry)
                    {
                        entry             = Math.Max(failSafeLongEntry + oneTick, curBar.Low);
                        exit              = 0;
                        curTrade          = trade.GoLong;
                        tradeProfitPoints = 0;
                        stop              = Math.Max(failSafeLongEntry + oneTick, curBar.Low) - ATRMultiplier * ATR;
                        entryUnits        = units;
                        lastTrade         = 0;
                    }
                    else
                    {
                        exit              = 0;
                        entry             = entry[1];
                        curTrade          = trade.SkipLong;
                        tradeProfitPoints = 0;
                        stop              = stop[1];
                        lastTrade         = lastTrade[1];
                        entryUnits        = 0;
                    }

                case trade.SkipShort:
                    if (curBar.High > shortExit || curBar.High > stop[1])
                    {
                        entryUnits        = 0;
                        exit              = Math.Max(curBar.Open, Math.Min(shortExit + oneTick, stop[1] + oneTick));
                        entry             = entry[1];
                        curTrade          = trade.Flat;
                        tradeProfitPoints = entry[1] - exit;
                        stop              = -1m;
                        lastTrade         = 0;
                    }
                    else if (curBar.Low < failSafeShortEntry)
                    {
                        entry             = Math.Min(failSafeShortEntry - oneTick, curBar.High);
                        exit              = 0;
                        curTrade          = trade.GoShort;
                        tradeProfitPoints = 0;
                        stop              = entry + ATRMultiplier * ATR;
                        entryUnits        = units;
                        lastTrade         = 0;
                    }
                    else
                    {
                        exit              = 0;
                        entry             = entry[1];
                        curTrade          = trade.SkipShort;
                        tradeProfitPoints = 0;
                        stop              = stop[1];
                        lastTrade         = lastTrade[1];
                        entryUnits        = 0;
                    }
                }
                break;

            case SystemType.System_Two:

                switch (trade[1])
                {
                case trade.Init:
                    lastTrade         = 0;
                    entry             = 0;
                    exit              = 0;
                    curTrade          = barNumber() >= 1 ? trade.Flat : trade.Init;
                    tradeProfitPoints = 0;
                    stop              = 0;
                    entryUnits        = unit;

                case trade.Flat:
                    if (curBar.High > failSafeLongEntry)
                    {
                        entry             = Math.Max(failSafeLongEntry + oneTick, curBar.Low);
                        exit              = 0;
                        curTrade          = trade.GoLong;
                        tradeProfitPoints = 0;
                        stop              = entry - ATRMultiplier * ATR;
                        entryUnits        = units;
                        lastTrade         = 0;
                    }
                    else if (curBar.Low < failSafeShortEntry)
                    {
                        entry             = Math.Min(failSafeShortEntry - oneTick, curBar.High);
                        exit              = 0;
                        curTrade          = trade.GoShort;
                        tradeProfitPoints = 0;
                        stop              = entry + ATRMultiplier * ATR;
                        entryUnits        = unit;
                        lastTrade         = 0;
                    }
                    else
                    {
                        entry             = 0;
                        exit              = 0;
                        curTrade          = trade.Flat;
                        tradeProfitPoints = 0;
                        stop              = -1m;
                        entryUnits        = entryUnits[1];
                        lastTrade         = 0;
                    }

                case trade.GoLong:
                    entryUnits = entryUnits[1];
                    if (curBar.Low < longExit || curBar.Low < stop[1])
                    {
                        exit              = Math.Min(curBar.Open, Math.Max(longExit - oneTick, stop[1] - oneTick));
                        entry             = entry[1];
                        curTrade          = trade.Flat;
                        tradeProfitPoints = exit - entry[1];
                        stop              = -1m;
                        lastTrade         = 0;
                    }
                    else
                    {
                        exit              = 0;
                        entry             = entry[1];
                        curTrade          = trade.GoLong;
                        tradeProfitPoints = 0;
                        stop              = stop[1];
                        lastTrade         = 0;
                    }

                case trade.GoShort:
                    entryUnits = entryUnits[1];
                    if (curBar.High > shortExit || curBar.High > stop[1])
                    {
                        exit              = Math.Max(curBar.Open, Math.Min(shortExit + oneTick, stop[1] + oneTick));
                        entry             = entry[1];
                        curTrade          = trade.Flat;
                        tradeProfitPoints = entry[1] - exit;
                        stop              = -1m;
                        lastTrade         = 0;
                    }
                    else
                    {
                        exit              = 0;
                        entry             = entry[1];
                        curTrade          = trade.GoShort;
                        tradeProfitPoints = 0;
                        stop              = stop[1];
                        lastTrade         = 0;
                    }

                case trade.SkipShort:
                    entryUnits        = 0;
                    exit              = 0;
                    entry             = 0;
                    curTrade          = trade.GoShort;
                    tradeProfitPoints = 0;
                    stop              = 0;
                    lastTrade         = 0;

                case trade.SkipLong:
                    entryUnits        = 0;
                    exit              = 0;
                    entry             = 0;
                    trade             = trade.GoShort;
                    tradeProfitPoints = 0;
                    stop              = 0;
                    lastTrade         = 0;
                }
                break;
            }

            //
            //           D("received new bar. close is "+ (blt[symbol].RecentBar.Close).ToString() +"SMA is "+SMA.ToString());


/*  for the moment let me assume we always get a fill
 *          //ensure we aren't waiting for previous order to fill
 *          if (!_wait[symbol])
 *          {
 *
 *              // if we're flat and not waiting
 *              if (pt[symbol].isFlat)
 *              {
 *                  // if our current price is above SMA, buy
 *                  if (blt[symbol].RecentBar.Close > ATR)
 *                  {
 *                      D("crosses above MA, buy");
 *                      sendorder(new BuyMarket(symbol, EntrySize));
 *                      // wait for fill
 *                      _wait[symbol] = true;
 *                  }
 *                  // otherwise if it's less than SMA, sell
 *                  if (blt[symbol].RecentBar.Close < ATR)
 *                  {
 *                      D("crosses below MA, sell");
 *                      sendorder(new SellMarket(symbol, EntrySize));
 *                      // wait for fill
 *                      _wait[symbol] = true;
 *                  }
 *              }
 *              else if ((pt[symbol].isLong && (blt[symbol].RecentBar.Close < SMA))
 || (pt[symbol].isShort && (blt[symbol].RecentBar.Close > SMA)))
 ||             {
 ||                 D("counter trend, exit.");
 ||                 sendorder(new MarketOrderFlat(pt[symbol]));
 ||                 // wait for fill
 ||                 _wait[symbol] = true;
 ||             }
 ||         }
 ||         else
 ||         {
 ||             D("no action, waiting for previous order to fill");
 ||         }
 */


            // this way we can debug our indicators during development
            // indicators are sent in the same order as they are named above
            sendindicators(new string[] { time.ToString(), SMA.ToString("N2") });

            // draw the MA as a line
            sendchartlabel(SMA, time);
        }
Esempio n. 22
0
        void blt_GotNewBar(string symbol, int interval)
        {
            // lets do our entries.

            int idx = _active.getindex(symbol);

            // calculate the SMA using closign prices for so many bars back
            decimal SMA = Calc.Avg(Calc.EndSlice(blt[symbol].Close(), _barsback));

            // uncomment to use TA-lib indicators
            //int num,si;
            //double[] result = new double[blt[symbol].Count];
            //Core.Sma(0, blt[symbol].Last,
            //    Calc.Decimal2Double(blt[symbol].Close()),
            //    _barsback,out si, out num, result);
            //Calc.TAPopulateGT(idx, num, ref result, _sma);
            //decimal SMA = _sma[idx];

            // wait until we have an SMA
            if (SMA == 0)
            {
                return;
            }

            //ensure we aren't waiting for previous order to fill
            if (!_wait[symbol])
            {
                // if we're flat and not waiting
                if (pt[symbol].isFlat)
                {
                    // if our current price is above SMA, buy
                    if (blt[symbol].RecentBar.Close > SMA)
                    {
                        D("crosses above MA, buy");
                        sendorder(new BuyMarket(symbol, EntrySize));
                        // wait for fill
                        _wait[symbol] = true;
                    }
                    // otherwise if it's less than SMA, sell
                    if (blt[symbol].RecentBar.Close < SMA)
                    {
                        D("crosses below MA, sell");
                        sendorder(new SellMarket(symbol, EntrySize));
                        // wait for fill
                        _wait[symbol] = true;
                    }
                }
                else if ((pt[symbol].isLong && (blt[symbol].RecentBar.Close < SMA)) ||
                         (pt[symbol].isShort && (blt[symbol].RecentBar.Close > SMA)))
                {
                    D("counter trend, exit.");
                    sendorder(new MarketOrderFlat(pt[symbol]));
                    // wait for fill
                    _wait[symbol] = true;
                }
            }



            // this way we can debug our indicators during development
            // indicators are sent in the same order as they are named above
            sendindicators(new string[] { time.ToString(), SMA.ToString("F2", System.Globalization.CultureInfo.InvariantCulture) });

            // draw the MA as a line
            sendchartlabel(SMA, time);
        }
Esempio n. 23
0
        internal static bool transform_assist_helpers(List <string> sourcetypes, GenericTracker <Token[]> const2tokens, ref GenericTracker <List <Token> > function2functoks)
        {
            // get destination class symbols
            var templateclasssym = RD_AssistTemplate.GetClassSymbols();

            // process every token
            for (int i = 0; i < tokstream.Count; i++)
            {
                // get our building blocks
                var tok = tokstream[i];
                // look for symbols
                if (!tok.isSymbol)
                {
                    continue;
                }
                // ignore constructors
                if (sourcetypes.Contains(tok.data))
                {
                    continue;
                }
                // skip methods we have overridden in destination class  (eg GetSymbolDecimal)
                if (templateclasssym.Contains(tok.data))
                {
                    continue;
                }
                // get previous token symbol
                var ptok = getprevioussymbol(tok);
                // verify we return an assist
                if (ptok.data != "AssistI")
                {
                    continue;
                }
                // update other states
                //bool isvoidmethod = issymbolvoidargumentmethod(tok);
                //if (isvoidmethod)
                //    continue;
                bool ismethod = issymbolmethod(tok);



                // take the non-void static methods which return assists and place them as helpers
                if (ismethod)
                {
                    // get name of function
                    var fname = tok.data;
                    // get function tokens including the argument list (but not the static token)
                    var allfunction = new List <Token>();
                    // save this name
                    var ftokens = getfunctiontokens(i);
                    // get the constants used by this helper
                    var consttoks = gethelperconstants(ftokens, const2tokens);
                    // build entire function starting with return arguments
                    allfunction.Add(new Token(tokentype.symbol, "AssistI"));
                    allfunction.Add(new Token(tokentype.space, " "));
                    // name
                    allfunction.Add(tok);
                    // arguments
                    allfunction.AddRange(getfunctionarguments(i));
                    // re-write any functions not present in destination
                    //var rewrittenbody = rewrite_nonlocalsymbols(ftokens, sourcetype);
                    // body
                    allfunction.Add(new Token(tokentype.line, h.line()));
                    allfunction.Add(new Token(tokentype.block_start, "{"));
                    allfunction.Add(new Token(tokentype.line, h.line()));
                    // constants
                    allfunction.AddRange(consttoks);
                    // code
                    allfunction.AddRange(ftokens);
                    // end body
                    allfunction.Add(new Token(tokentype.line, h.line()));
                    allfunction.Add(new Token(tokentype.block_end, "}"));
                    allfunction.Add(new Token(tokentype.line, h.line()));
                    // get code from these modified tokens
                    //var bodycode = gettokencode(allfunction.ToArray());
                    // see if we have some code already
                    int tokencodeidx = function2functoks.getindex(tok.data);

                    // if not, save it
                    if (tokencodeidx < 0)
                    {
                        tokencodeidx = function2functoks.addindex(tok.data, allfunction);
                    }
                    else // otherwise it's an overload, append it
                    {
                        function2functoks[tokencodeidx].AddRange(allfunction);
                    }
                }
            }



            return(true);
        }
        void blt_GotNewBar(string symbol, int interval)       //K线的周期是可以自己定的,在Gottick中累计到周期后,就会自动进入GotNewBar中
        {
            //symbol是合约名字
            int  idx    = _active.getindex(symbol); //系统变量,一般是1
            Tick tOther = _kt[symbol];              //取到最新的tick,包含成交价,买1价,卖1价,买卖量等等

            // calculate the SMA using closign prices for so many bars back
            decimal ShortSMA = decimal.MinValue;
            decimal LongSMA  = decimal.MinValue;
            BarList _myBars  = _blt[symbol, interval]; //这一天所有的K线
            // make sure the lastBar is full
            Bar _lastBar = _myBars[_myBars.Count - 2]; //取倒数第2个,一个是因为零索引,还有一个就是比如现在是10点,
            //那么在10点零1分的第1秒组成了10点钟的K线,所以要往回取一个
            //-----------调用ATR独有的部分------------------------------
            decimal ATR          = decimal.MinValue;
            Bar     _previousBar = _myBars[_myBars.Count - 3]; // 前一个bar
            //----------------------------------------------------------
            bool isReverse = false;                            //false

            if (UseSMAFromATSGlobalIndicator)
            {
                _ShortSMAFromATSGlobalIndicator.UpdateValue(_lastBar.Close); //UpdateValue是连接response和indicator的重要函数
                //通过UpdateValue把昨天的收盘价传给Indicator
                ShortSMA = _ShortSMAFromATSGlobalIndicator.GetSignal();      //把计算好的SMA传回Response中
                _LongSMAFromATSGlobalIndicator.UpdateValue(_lastBar.Close);  //UpdateValue是连接response和indicator的重要函数
                //通过UpdateValue把昨天的收盘价传给Indicator
                LongSMA = _LongSMAFromATSGlobalIndicator.GetSignal();        //把计算好的SMA传回Response中
                //-----------------------------
                decimal firstRange  = _lastBar.High - _lastBar.Low;
                decimal secondRange = Math.Abs(_lastBar.High - _previousBar.Close);
                decimal thirdRange  = Math.Abs(_lastBar.Low - _previousBar.Close);
                decimal TR          = Math.Max(firstRange, Math.Max(secondRange, thirdRange));

                // deal with some outlier
                if (firstRange < 0)
                {
                    return;
                }

                _ATRFromATSGlobalIndicator.UpdateValue(TR);          // update ATR value
                ATR = _ATRFromATSGlobalIndicator.GetSignal();        // get the updated ATR value
                //--------------------------------
            }
            else
            {
                ShortSMA = Calc.Avg(Calc.EndSlice(_blt[symbol].Open(), _shortbarsback));
                LongSMA  = Calc.Avg(Calc.EndSlice(_blt[symbol].Open(), _shortbarsback + _incrementbarsback));
            }
            // wait until we have an SMA
            if (ShortSMA == 0 || LongSMA == 0)
            {
                return;
            }

            if (_LastLongSMA == decimal.MinValue || _LastShortSMA == decimal.MinValue)
            {
                _LastShortSMA = ShortSMA;
                _LastLongSMA  = LongSMA;
                return;
            }

            //---------------给highestprice赋值--------
            if (_highestprice < _lastBar.High)
            {
                _highestprice = _lastBar.High;
            }
            if (_highestcloseprice < _lastBar.Close)
            {
                _highestcloseprice = _lastBar.Close;
            }
            //-----------------------------------------

            //ensure we aren't waiting for previous order to fill
            if (!_wait[symbol])  //如果有挂单,不要再发信号
            {
                // if we're flat and not waiting
                if (_pt[symbol].isFlat)                      //空仓
                {
                    // if our current price is above SMA, buy
                    if (_LastShortSMA < _LastLongSMA && ShortSMA > LongSMA)
                    {
                        D("Short SMA crosses above Long SMA , buy");
                        //sendorder(new BuyMarket(symbol, EntrySize));
                        _side = true;                                                                                            //true就是买入
                        _adj  = (_side ? -1 : +1) * _quasiMarketOrderAdjSize;                                                    //为了达成成交需要的一串代码,先照抄,以后再理解
                        Int64      _orderidLocal = _idtLocal.AssignId;                                                           //记录orderid 照抄
                        LimitOrder lOrder        = new LimitOrder(symbol, _side, EntrySize, tOther.trade - _adj, _orderidLocal); //生成这一个订单,entrysize是下单量,t是价格
                        sendorder(lOrder);                                                                                       //把订单发出去         系统的空仓和平仓是一样的,如果想从多仓1手变成空仓1手,entrysize乘2就好了
                        // wait for fill
                        _wait[symbol]  = true;                                                                                   //记录一下这个单已经发出去了
                        _currentEntry += 1;
                    }
                    // otherwise if it's less than SMA, sell
                    if (_LastShortSMA > _LastLongSMA && ShortSMA < LongSMA)
                    {
                        D("Long SMA crosses above Short SMA , sell");
                        //sendorder(new SellMarket(symbol, EntrySize));
                        _side = false;                                       //和上面相反
                        _adj  = (_side ? -1 : +1) * _quasiMarketOrderAdjSize;
                        Int64      _orderidLocal = _idtLocal.AssignId;
                        LimitOrder lOrder        = new LimitOrder(symbol, _side, EntrySize, tOther.trade - _adj, _orderidLocal);
                        sendorder(lOrder);
                        // wait for fill
                        _wait[symbol]  = true;
                        _currentEntry -= 1;
                    }
                }
                else if ((_pt[symbol].isLong && (_LastShortSMA > _LastLongSMA && ShortSMA < LongSMA)) ||
                         (_pt[symbol].isShort && (_LastShortSMA <_LastLongSMA && ShortSMA> LongSMA)))
                {
                    int reverse = 1;
                    if (isReverse)
                    {
                        reverse = Math.Abs(_currentEntry) * 2;  //等于1的话恢复算法
                    }
                    D("counter trend, exit.");
                    //sendorder(new MarketOrderFlat(pt[symbol]));
                    _side = !_pt[symbol].isLong;
                    _adj  = (_side ? -1 : +1) * _quasiMarketOrderAdjSize;
                    Int64      _orderidLocal = _idtLocal.AssignId;
                    LimitOrder lOrder        = new LimitOrder(symbol, _side, EntrySize * reverse, tOther.trade - _adj, _orderidLocal);
                    sendorder(lOrder);
                    // wait for fill
                    _wait[symbol] = true;
                    _currentEntry = -_currentEntry;
                }

                /*//-------------------综合使用YOYO止损法和吊灯止损法--------------------
                 * if ((!_pt[symbol].isFlat && _lastBar.Close < _highestprice - 3 * ATR)
                 || (!_pt[symbol].isFlat && _lastBar.Close < _highestcloseprice - (decimal)2.5 * ATR) ||
                 ||  (!_pt[symbol].isFlat && _lastBar.Close < _previousBar.Close - (decimal)2* ATR))
                 ||{
                 ||  int stop = Math.Abs(_currentEntry);
                 ||  D("It's time to stop.");
                 ||  _side = !_pt[symbol].isLong;
                 ||  _adj = (_side ? -1 : +1) * _quasiMarketOrderAdjSize;
                 ||  Int64 _orderidLocal = _idtLocal.AssignId;
                 ||  LimitOrder lOrder = new LimitOrder(symbol, _side, EntrySize * stop, tOther.trade - _adj, _orderidLocal);
                 ||  sendorder(lOrder);
                 ||  // wait for fill
                 ||  _wait[symbol] = true;
                 ||  _currentEntry = 0;
                 ||}*/
                //------------------------------------------------------------------
            }

            // this way we can debug our indicators during development
            // indicators are sent in the same order as they are named above
            sendindicators(new string[] { _time.ToString(),
                                          ShortSMA.ToString("F5", System.Globalization.CultureInfo.InvariantCulture),
                                          LongSMA.ToString("F5", System.Globalization.CultureInfo.InvariantCulture),
                                          _lastBar.Close.ToString("F5", System.Globalization.CultureInfo.InvariantCulture) });
            //打印在bench的indicator中
            _LastLongSMA  = LongSMA;
            _LastShortSMA = ShortSMA;
        }
Esempio n. 25
0
        public void FireTick(string[] actualData)
        {
            if (actualData.Length < 66)
            {
                return;
            }
            try
            {
                if (actualData[0] == "F")
                {
                    return;
                }

                Tick tick = new TickImpl();
                tick.date = Util.ToTLDate();
                DateTime now;
                int      local = Util.ToTLTime();
                if (DateTime.TryParse(actualData[65], out now))
                {
                    tick.time = Util.DT2FT(now);

                    if (ReportLatency)
                    {
                        Int64 latency = 0;
                        if (lastticktime != 0)
                        {
                            latency = DateTime.Now.Ticks - lastticktime;
                        }
                        lastticktime = now.Ticks;

                        latencyavg = (latency + latencyavg) / 2;
                        tickssincelastlatencyreport++;
                        // test for peak
                        if (latency > peaklatency)
                        {
                            peaklatency = latency;
                        }
                        // test for report
                        if (tickssincelastlatencyreport > 500000)
                        {
                            // convert to ms
                            double latencyms = latencyavg / 10000;
                            double peakms    = peaklatency / 10000;
                            debug(string.Format("latency (ms) avg {0:N1} peak: {0:N1}", latencyms, peaklatency));
                            tickssincelastlatencyreport = 0;
                            latencyavg = 0;
                        }
                    }
                }
                else
                {
                    tick.time = local;
                }
                // see if user has tick ignoring enabled
                //(this is because in early AM iqfeed will frequently send ticks with yesterday time stamps
                if (usebeforeafterignoretime)
                {
                    // ensure that ordering works across multiple days
                    if (lasttickdate != tick.date)
                    {
                        lasttickordertime = 0;
                        lasttickdate      = tick.date;
                    }

                    // see if tick should be ignored
                    if ((local < IfBeforeTimeUseIgnoreAfter) &&
                        (tick.time > IgnoreAfterTimeWithBefore))
                    {
                        return;
                    }
                    // allow ignoring for ignoring other ticks that are out of order
                    else if (ignoreoutoforder && (tick.time < lasttickordertime))
                    {
                        return;
                    }
                    lasttickordertime = tick.time;
                }

                int v = 0;
                if (int.TryParse(actualData[64], out v))
                {
                    tick.oe = getmarket(v);
                }
                if (int.TryParse(actualData[63], out v))
                {
                    tick.be = getmarket(v);
                }
                if (int.TryParse(actualData[62], out v))
                {
                    tick.ex = getmarket(v);
                }
                tick.symbol  = actualData[1];
                tick.bid     = Convert.ToDecimal(actualData[10]);
                tick.ask     = Convert.ToDecimal(actualData[11]);
                tick.trade   = Convert.ToDecimal(actualData[3]);
                tick.size    = Convert.ToInt32(actualData[7]);
                tick.BidSize = Convert.ToInt32(actualData[12]);
                tick.AskSize = Convert.ToInt32(actualData[13]);
                // get symbol index for custom data requests
                int idx = _highs.getindex(tick.symbol);
                // update custom data (tryparse is faster than convert)
                decimal d = 0;
                if (decimal.TryParse(actualData[8], out d))
                {
                    _highs[idx] = d;
                }
                if (decimal.TryParse(actualData[9], out d))
                {
                    _lows[idx] = d;
                }
                if (isPaperTradeEnabled)
                {
                    ptt.newTick(tick);
                }
                tl.newTick(tick);
            }
            catch (Exception ex)
            {
                debug("Tick error: " + string.Join(",", actualData));
                debug(ex.Message + ex.StackTrace);
            }
        }
Esempio n. 26
0
        static unsafe void OnNxCoreTrade(NxCoreSystem *pNxCoreSys, NxCoreMessage *pNxCoreMsg)
        {
            if (keepcurrent && (STATUS < 4))
            {
                return;
            }
            if (DOLIVESKIPTEST)
            {
                if (pNxCoreSys->nxTime.MsOfDay < (DateTime.UtcNow.TimeOfDay.TotalMilliseconds - (DateTime.Now.IsDaylightSavingTime() ? (1000 * 60 * 60 * 4) : (1000 * 60 * 60 * 5))))
                {
                    return;
                }
                DOLIVESKIPTEST = false;
                D("NxCore starting realtime data");
            }
            // Get the symbol for category message

            int idx = _nxsyms.getindex(new string(&pNxCoreMsg->coreHeader.pnxStringSymbol->String));

            if (idx < 0)
            {
                return;
            }
            if (!_nxsyms[idx])
            {
                return;
            }
            // Assign a pointer to the Trade data
            NxCoreTrade *Trade = &pNxCoreMsg->coreData.Trade;
            // Get the price and net change
            double Price = NxCore.PriceToDouble(Trade->Price, Trade->PriceType);
            //double NetChange = NxCore.PriceToDouble(Trade->NetChange, Trade->PriceType);
            NxTime time   = pNxCoreMsg->coreHeader.nxExgTimestamp;
            int    tltime = time.Hour * 10000 + time.Minute * 100 + time.Second;
            NxDate date   = pNxCoreMsg->coreHeader.nxSessionDate;
            int    tldate = (int)date.Year * 10000 + (int)date.Month * 100 + (int)date.Day;
            string ex     = excode2name(pNxCoreMsg->coreHeader.ReportingExg);
            int    size   = (int)Trade->Size;

            // check for index
            if (size <= 0)
            {
                return;
            }
            Tick k = new TickImpl();

            k.symbol = _realsym2nxidx.getlabel(idx);
            k.date   = tldate;
            k.time   = tltime;
            k.trade  = (decimal)Price;
            k.ex     = ex;
            k.size   = size;
            try
            {
                tl.newTick(k);
            }
            catch (Exception e)
            {
                D("bad tick: " + k.symbol + " " + Price + " " + size + " " + ex + " " + e.Message + e.StackTrace);
            }
        }
Esempio n. 27
0
        private void FireTick(string[] actualData)
        {
            if (actualData.Length < 66)
            {
                return;
            }
            try
            {
                if (actualData[0] == "F")
                {
                    return;
                }

                Tick tick = new TickImpl();
                tick.date = Util.ToTLDate();
                DateTime now;
                if (DateTime.TryParse(actualData[65], out now))
                {
                    tick.time = Util.DT2FT(now);
                }
                else
                {
                    tick.time = Util.ToTLTime();
                }
                int v = 0;
                if (int.TryParse(actualData[64], out v))
                {
                    tick.oe = getmarket(v);
                }
                if (int.TryParse(actualData[63], out v))
                {
                    tick.be = getmarket(v);
                }
                if (int.TryParse(actualData[62], out v))
                {
                    tick.ex = getmarket(v);
                }
                tick.symbol  = actualData[1];
                tick.bid     = Convert.ToDecimal(actualData[10]);
                tick.ask     = Convert.ToDecimal(actualData[11]);
                tick.trade   = Convert.ToDecimal(actualData[3]);
                tick.size    = Convert.ToInt32(actualData[7]);
                tick.BidSize = Convert.ToInt32(actualData[12]);
                tick.AskSize = Convert.ToInt32(actualData[13]);
                // get symbol index for custom data requests
                int idx = _highs.getindex(tick.symbol);
                // update custom data (tryparse is faster than convert)
                decimal d = 0;
                if (decimal.TryParse(actualData[8], out d))
                {
                    _highs[idx] = d;
                }
                if (decimal.TryParse(actualData[9], out d))
                {
                    _lows[idx] = d;
                }
                if (isPaperTradeEnabled)
                {
                    tl.newTick(tick);
                }
                tl.newTick(tick);
            }
            catch (Exception ex)
            {
                debug("Tick error: " + string.Join(",", actualData));
                debug(ex.Message + ex.StackTrace);
            }
        }
Esempio n. 28
0
 /// <summary>
 /// populate generic tracker with most recent TA-lib result
 /// </summary>
 /// <param name="sym"></param>
 /// <param name="nb"></param>
 /// <param name="res"></param>
 /// <param name="gt"></param>
 /// <returns></returns>
 public static bool TAPopulateGT(string sym, int nb, ref double[] res, GenericTracker<decimal> gt)
 {
     int idx = gt.getindex(sym);
     return TAPopulateGT(idx, nb, 2, ref res, gt);
 }
Esempio n. 29
0
        void tl_newRegisterSymbols(string client, string symbols)
        {
            D("got subscribe request: " + client + ": " + symbols);


            // ensure new symbols are added
            Basket newb = tl.AllClientBasket;

            // ensure we have an id
            foreach (string sym in newb.ToSymArray())
            {
                Security sec = SecurityImpl.Parse(sym);
                char     p;
                if (sec.Type == SecurityType.STK)
                {
                    p = 'e';
                }
                else if (sec.Type == SecurityType.BND)
                {
                    p = 'b';
                }
                else if (sec.Type == SecurityType.FUT)
                {
                    p = 'f';
                }
                else if (sec.Type == SecurityType.IDX)
                {
                    p = 'i';
                }
                else if (sec.Type == SecurityType.OPT)
                {
                    p = 'o';
                }
                else if (sec.Type == SecurityType.CASH)
                {
                    p = 'c';
                }
                else if (sec.Type == SecurityType.FOP)
                {
                    p = 'p';
                }
                else
                {
                    p = 'e';
                }
                string nxsym = p + sec.symbol;
                int    idx   = _nxsyms.addindex(nxsym, true);
                _realsym2nxidx.addindex(sec.symbol, idx);
            }
            // ensure old symbols are removed
            if (old.Count > 0)
            {
                Basket rem = BasketImpl.Subtract(old, newb);
                foreach (Security s in rem)
                {
                    int idx = _realsym2nxidx.getindex(s.symbol);
                    if (idx < 0)
                    {
                        debug("Unable to locate subscription for: " + s.symbol);
                        continue;
                    }
                    _nxsyms[idx] = false;
                }
            }
            // save new as old
            old = newb;
        }
        void GotNewBar(string symbol, int interval)
        {
            // get current barlist for this symbol+interval
            BarList bl = track_barlists[symbol, interval];

            // issue an event (todo: should I put this functionality into MessageResponseTemplate.cs? or should I get rid of GotNewBar at all? hmm...) will stay here for a while..
            BsonDocument bson_doc = new BsonDocument();

            bson_doc             = new BsonDocument();
            bson_doc["Symbol"]   = bl.RecentBar.Symbol;
            bson_doc["High"]     = bl.RecentBar.High.ToString();
            bson_doc["Low"]      = bl.RecentBar.Low.ToString();
            bson_doc["Open"]     = bl.RecentBar.Open.ToString();
            bson_doc["Close"]    = bl.RecentBar.Close.ToString();
            bson_doc["Volume"]   = bl.RecentBar.Volume.ToString();
            bson_doc["isNew"]    = bl.RecentBar.isNew;
            bson_doc["Bartime"]  = bl.RecentBar.Bartime;
            bson_doc["Bardate"]  = bl.RecentBar.Bardate;
            bson_doc["isValid"]  = bl.RecentBar.isValid;
            bson_doc["Interval"] = bl.RecentBar.Interval;
            bson_doc["time"]     = bl.RecentBar.time;

            //send_event(MimeType.got_new_bar, "bar", bson_doc.ToString());
            log_file.WriteLine("got_new_bar" + bson_doc.ToString());

            // get index for symbol
            int idx = track_symbols.getindex(symbol);

            string dbg_msg = "GotNewBar(" + symbol + ", " + interval + "):";

            // check for first cross on first interval
            if (interval == _response_barsize_s)
            {
                decimal ema = Calc.Avg(Calc.EndSlice(bl.Close(), _ema_bar));

                track_ema[symbol].Add(ema);

                // drawings...
                if (bl.Close().Length > _ema_bar)
                {
                    // draw 2 sma lines:
                    sendchartlabel(ema, time, System.Drawing.Color.FromArgb(0xff, 0x01, 0x01));

                    // do the trade (if required)
                    decimal[] ema_arr = track_ema[symbol].ToArray();

                    decimal prev_ema  = ema_arr[ema_arr.Length - 2];
                    decimal curr_ema  = ema_arr[ema_arr.Length - 1];
                    decimal delta_ema = curr_ema - prev_ema;

                    // sma just crossed?
                    bool should_buy  = track_positions[symbol].isFlat && delta_ema >= 0.002m;
                    bool should_sell = false;

                    dbg_msg += " delta_ema=" + delta_ema.ToString("000.000");

                    /*
                     * dbg_msg += " fast=" + curr_sma_fast.ToString("000.000");
                     * dbg_msg += " pr_slow=" + prev_sma_slow.ToString("000.000");
                     * dbg_msg += " pr_fast=" + prev_sma_fast.ToString("000.000");
                     * dbg_msg += " [" + symbol + "].isFlat=" + track_positions[symbol].isFlat.ToString();
                     * dbg_msg += " track_positions[symbol].ToString=" + track_positions[symbol].ToString();
                     * dbg_msg += " should_buy=" + should_buy.ToString();
                     * dbg_msg += " should_sell=" + should_sell.ToString();
                     */

                    //senddebug("GotNewBar(): " + debug_position_tracker(symbol));

                    if (should_buy)
                    {
                        // come buy some! (c) Duke Nukem
                        string comment = " BuyMarket(" + symbol + ", " + EntrySize.ToString() + ")";
                        sendorder(new BuyMarket(symbol, EntrySize, comment));
                        log_file.WriteLine("close position: " + comment);
                        dbg_msg += comment;
                    }

                    if (false)                                              // we do all the selling on tick()
                    {
                        if (!track_positions[symbol].isFlat && should_sell) // we don't short, so also check if !flat
                        //if ( should_sell) // we don't short, so also check if !flat
                        {
                            sendorder(new SellMarket(symbol, EntrySize));
                            dbg_msg += " SellMarket(" + symbol + ", " + EntrySize.ToString() + ")";
                        }
                    }
                }
            }
            //else
            //{
            //    //
            //    dbg_msg += "GotNewBar() other interval=" + interval;
            //}

            // spit out one dbg message line per bar
            D(dbg_msg);

            // nice way to notify of current tracker values
            sendindicators(gt.GetIndicatorValues(idx, gens()));
            return;
        }
Esempio n. 31
0
        public static bool PlayHistoricalTicks(Response r, GenericTracker<string> symbols, DateTime start, DateTime endexclusive, int expecteddays, DebugDelegate deb)
        {
            bool skipexpected = expecteddays == 0;
            // prepare to track actual days for each symbol
            GenericTracker<int> actualdays = new GenericTracker<int>();
            foreach (string sym in symbols)
                actualdays.addindex(sym, 0);
            // prepare to track all tickfiles
            Dictionary<string, List<string>> files = new Dictionary<string, List<string>>();
            // get all required tickfiles for each symbol on each date
            DateTime now = new DateTime(start.Ticks);
            int tfc = 0;
            while (now < endexclusive)
            {
                // get the tick files
                List<string> allfiles = TikUtil.GetFilesFromDate(Util.TLTickDir, Util.ToTLDate(now));
                // go through them all and see if we find expected number
                foreach (string fn in allfiles)
                {
                    // get security
                    SecurityImpl sec = SecurityImpl.FromTIK(fn);
                    // see if we want this symbol
                    int idx = symbols.getindex(sec.HistSource.RealSymbol);
                    if (idx < 0)
                        idx = symbols.getindex(sec.Symbol);
                    sec.HistSource.Close();
                    // skip if we don't
                    if (idx < 0)
                        continue;
                    string sym = symbols.getlabel(idx);
                    // if we have it, count actual day
                    actualdays[idx]++;
                    // save file and symbol
                    if (!files.ContainsKey(sym))
                        files.Add(sym, new List<string>());
                    files[sym].Add(fn);
                    // count files
                    tfc++;
                }
                // add one day
                now = now.AddDays(1);
            }
            // notify
            if (deb != null)
            {
                deb("found " + tfc + " tick files matching dates: " + Util.ToTLDate(start) + "->" + Util.ToTLDate(endexclusive) + " for: " + string.Join(",", symbols.ToArray()));
            }
            // playback when actual meets expected
            bool allok = true;
            foreach (string sym in symbols)
            {
                if (skipexpected || (actualdays[sym] >= expecteddays))
                {
                    // get tick files
                    string[] tf = files[sym].ToArray();
                    // notify
                    if (deb != null)
                    {
                        deb(sym + " playing back " + tf.Length + " tick files.");
                    }
                    // playback
                    HistSim h = new SingleSimImpl(tf);
                    h.GotTick += new TickDelegate(r.GotTick);
                    h.PlayTo(MultiSimImpl.ENDSIM);
                    h.Stop();
                    // notify
                    if (deb != null)
                    {
                        deb(sym + " completed playback. ");
                    }
                }
                else
                    allok = false;
            }


            return allok;

        }
        void GotNewBar(string symbol, int interval)
        {
            //if (symbol.ToUpper() != "ABX") return;

            // get current barlist for this symbol+interval
            BarList bl = track_barlists[symbol, interval];

            // get index for symbol
            int idx = track_symbols.getindex(symbol);

            string dbg_msg = "GotNewBar(" + symbol + ", " + interval + "):";

            // check for first cross on first interval
            if (interval == (int)BarInterval.Minute)
            {
                decimal no_tracker_slow_ma = Calc.Avg(Calc.EndSlice(bl.Close(), _slow_ma_bar));
                decimal no_tracker_fast_ma = Calc.Avg(Calc.EndSlice(bl.Close(), _fast_ma_bar));

                track_sma_slow[symbol].Add(no_tracker_slow_ma);
                track_sma_fast[symbol].Add(no_tracker_fast_ma);

                // drawings...
                if (bl.Close().Length > 1)
                {
                    // this is how we draw line, which connects all bars close.
                    //decimal val = bl.Close()[bl.Close().Length - 2]; // length-1 would be last, so length-2 is our previus bar
                    //int time_prev = bl.Time()[bl.Time().Length - 2];
                    //sendchartlabel(val, time_prev, System.Drawing.Color.Green);

                    // draw 2 sma lines:
                    sendchartlabel(no_tracker_slow_ma, time, System.Drawing.Color.Blue);
                    sendchartlabel(no_tracker_fast_ma, time, System.Drawing.Color.FromArgb(0xff, 0x01, 0x01)); // wtf? why red line multiplies after each sell order?!

                    //sendchartlabel(bl.Close()[bl.Close().Length - 2],
                    //    time,
                    //    (time - 60).ToString(),
                    //    System.Drawing.Color.Green);

                    // do the trade (if required)
                    decimal[] sma_slow = track_sma_slow[symbol].ToArray();
                    decimal[] sma_fast = track_sma_fast[symbol].ToArray();

                    decimal prev_sma_slow = sma_slow[sma_slow.Length - 2];
                    decimal prev_sma_fast = sma_fast[sma_fast.Length - 2];

                    decimal curr_sma_slow = sma_slow[sma_slow.Length - 1]; // imho quite ugly..
                    decimal curr_sma_fast = sma_fast[sma_fast.Length - 1]; // todo: read more on how to work with Lists

                    // sma just crossed?
                    bool should_buy = prev_sma_slow > prev_sma_fast && curr_sma_slow < curr_sma_fast;
                    bool should_sell = prev_sma_slow <prev_sma_fast && curr_sma_slow> curr_sma_fast;

                    dbg_msg += " slow=" + curr_sma_slow.ToString("000.000");
                    dbg_msg += " fast=" + curr_sma_fast.ToString("000.000");
                    dbg_msg += " pr_slow=" + prev_sma_slow.ToString("000.000");
                    dbg_msg += " pr_fast=" + prev_sma_fast.ToString("000.000");
                    dbg_msg += " [" + symbol + "].isFlat=" + track_positions[symbol].isFlat.ToString();
                    dbg_msg += " track_positions[symbol].ToString=" + track_positions[symbol].ToString();
                    dbg_msg += " should_buy=" + should_buy.ToString();
                    dbg_msg += " should_sell=" + should_sell.ToString();

                    //senddebug("GotNewBar(): " + debug_position_tracker(symbol));

                    if (should_buy)
                    {
                        // come buy some! (c) Duke Nukem
                        sendorder(new BuyMarket(symbol, EntrySize));
                        dbg_msg += " BuyMarket(" + symbol + ", " + EntrySize.ToString() + ")";
                    }

                    if (!track_positions[symbol].isFlat && should_sell) // we don't short, so also check if !flat
                    //if ( should_sell) // we don't short, so also check if !flat
                    {
                        sendorder(new SellMarket(symbol, EntrySize));
                        dbg_msg += " SellMarket(" + symbol + ", " + EntrySize.ToString() + ")";
                    }
                }
            }
            //else
            //{
            //    //
            //    dbg_msg += "GotNewBar() other interval=" + interval;
            //}

            // spit out one dbg message line per bar
            //senddebug(dbg_msg);

            // nice way to notify of current tracker values
            sendindicators(gt.GetIndicatorValues(idx, gens()));
            return;
        }