Пример #1
0
        void GotNewBar(string symbol, int interval)
        {
            // get index for symbol
            int idx = indicatorcross2.addindex(symbol);
            // get current barlist for this symbol+interval
            BarList bl = blt[symbol, interval];

            // 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 (also showed failed rules)
            if (gt.rulepasses(idx, "sequential buy entry", senddebug, true, first1then2ok, indicatorcross2, indicatorcross1))
            {
                sendorder(new BuyMarket(symbol, 100));
            }
        }
 void track_symbols_NewTxt(string txt, int idx)
 {
     // index all the trackers we're using
     track_positions.addindex(txt);
     track_sma_slow.addindex(txt, new List <decimal>());
     track_sma_fast.addindex(txt, new List <decimal>());
 }
Пример #3
0
        public static GenericTracker <Screener> fetchscreen(string url, DebugDelegate deb)
        {
            // get raw list
            string[][] raw = fetchrawlist(url, deb);
            debug("beginning screen indexing of " + raw.GetLength(0) + " screens.");
            GenericTracker <Screener> ss = new GenericTracker <Screener>(raw.GetLength(0), "SCREENS", new Screener());
            int l = 0;

            foreach (string[] r in raw)
            {
                l++;
                Screener s = getscreen_qdl(r);
                if (s.isValid)
                {
                    ss.addindex(s.symbol, s);
                }
                else
                {
/*
 *                  if (r!=null)
 *                      debug("ignoring invalid screen line#"+l.ToString("N0")+" with data: " + Util.join(r));
 *                  else
 *                      debug("ignoring invalid screen line#" + l.ToString("N0") + " with no data.");
 */
                }
            }
            debug("completed index of " + ss.Count + " screens.");
            return(ss);
        }
        public override void GotTick(Tick tick)           //数据进来,先进gottick,如果需要对成交价等进行更改,在gottick里进行
        {
            // keep track of time from tick

            _time = tick.time;
            if (_date > tick.date)
            {
                // this is important for consistency between runs for ATSTestBench and ATSTestBenchBatch
                Reset();
            }
            _date = tick.date;
            // ensure response is active
            if (!isValid)
            {
                return;
            }
            // ensure we are tracking active status for this symbol
            int idx = _active.addindex(tick.symbol, true);

            // if we're not active, quit
            if (!_active[idx])
            {
                return;
            }
            // check for shutdown time
            // apply bar tracking to all ticks that enter
            _kt.newTick(tick);
            _blt.newTick(tick);

            // ignore anything that is not a trade
            if (!tick.isTrade)
            {
                return;                      //如果没有trade,这个数据是用不到的
            }
        }
Пример #5
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>
        /// 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();
        }
Пример #7
0
        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);
        }
Пример #8
0
 public override void GotTick(Tick tick)
 {
     // track order ids
     _orderid.addindex(tick.symbol, 0);
     // track ticks
     _kt.newTick(tick);
     // see if we need to send an order
     if (_orderid[tick.symbol] == 0)
     {
         // get complete last tick for this symbol
         Tick k = _kt[tick.symbol];
         // see if we have proper info to place order
         if ((Side && k.hasBid) || (!Side && k.hasAsk))
         {
             _orderid[tick.symbol] = _idt.NextId;
             D(tick.symbol + " sending limit order: " + _orderid[tick.symbol]);
             sendorder(new LimitOrder(tick.symbol, Side, Ordersize, Side ? k.bid - Distance : k.ask + Distance, _idt.AssignId));
         }
     }
     else // otherwise increment counter
     {
         _tickcounter[tick.symbol]++;
     }
     // see if we need to cancel
     if (_tickcounter[tick.symbol] > Frequency)
     {
         D(tick.symbol + " hit frequency, canceling: " + _orderid[tick.symbol]);
         sendcancel(_orderid[tick.symbol]);
     }
 }
Пример #9
0
        /// <summary>
        /// takes all or part of quandl object and converts it into GT
        /// </summary>
        /// <param name="ro"></param>
        /// <param name="datecol"></param>
        /// <param name="valcol"></param>
        /// <param name="startrow"></param>
        /// <param name="endrow"></param>
        /// <returns></returns>
        public static GenericTracker<decimal> Qdl2GT(RootObject ro, string datecol, string valcol, int startrow, int endrow, DebugDelegate d)
        {
            // get columns
            var datecolidx = GetQdlColidx(ro,datecol);
            var valcolidx = GetQdlColidx(ro,valcol);
            // slice out the data
            var subset = GetAllRows(ro, startrow, endrow, d);
            // get date column
            var dates = QdlCol2Dates( GetColumn(subset, datecolidx));
            var vals =QdlCol2Vals( GetColumn(subset, valcolidx));
            // populate GT
            GenericTracker<decimal> gt = new GenericTracker<decimal>(dates.Count);
            for (int i = 0; i < dates.Count; i++)
            {
                var val = vals[i];
                var dt = dates[i];
                if (val == qh.ERROR_VALUE)
                    continue;
                if (dt == qh.ERROR_DATE)
                    continue;
                var tldate = Util.ToTLDate(dt);
                gt.addindex(tldate.ToString("F0"), val);
                

            }
            return gt;

            

            
        }
Пример #10
0
 void PRIMARY_NewTxt(string txt, int idx)
 {
     // index all the trackers we're using
     pt.addindex(txt);
     expectedsize.addindex(txt);
     entryok.addindex(txt);
     pt.addindex(txt);
     indicatorcross1.addindex(txt);
     indicatorcross2.addindex(txt);
 }
Пример #11
0
        public override void GotTick(Tick k)
        {
            // get index from symbol, add if it doesn't exist
            int idx = PRIMARY.addindex(k.symbol, k.symbol);

            // build bars
            blt.newTick(k);
            // update whether entries are allowed
            entryok[idx] = expectedsize[idx] == pt[idx].Size;
        }
Пример #12
0
        /// <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;
            }
        }
        // Don't forget to add trackers to index automatically into following f-n.
        // Note: some trackers, like 'tick' and 'position' don't need to be here)
        //
        // link all the generic trackers together so we create
        // proper default values for each whenever we add symbol to one
        void track_symbols_NewTxt(string txt, int idx)
        {
            track_exitsignals.addindex(txt, false);
            // add other trackers here...

            //            in LessonGenericTrackers.cs
            //we index this:
            //       PositionTracker pt = new PositionTracker();

            //, but we don't index this:
            //       BarListTracker blt = new BarListTracker(new BarInterval[] { BarInterval.FiveMin, BarInterval.Minute });

            //how do I know which trackers should/must be indexed and which are not?
        }
Пример #14
0
        public static GenericTracker <Screener> fetchscreen(string url, DebugDelegate deb)
        {
            // get raw list
            string[][] raw = fetchrawlist(url, deb);
            debug("beginning screen indexing of " + raw.GetLength(0) + " screens.");
            GenericTracker <Screener> ss = new GenericTracker <Screener>(raw.GetLength(0), "SCREENS");

            foreach (string[] r in raw)
            {
                Screener s = getscreen(r);
                ss.addindex(s.symbol, s);
            }
            debug("completed index of " + ss.Count + " screens.");
            return(ss);
        }
Пример #15
0
        /*
         *     // turn on bar tracking
         *     BarListTracker blt = new BarListTracker();
         *     // turn on position tracking
         *     PositionTracker pt = new PositionTracker();
         *     // keep track of time for use in other functions
         *     int time = 0;
         */
        // got tick is called whenever this strategy receives a tick
        public override void GotTick(Tick tick)
        {
            _iTick++;
            // keep track of time from tick
            time = tick.time;
            // ensure response is active
            if (!isValid)
            {
                return;
            }
            // ensure we are tracking active status for this symbol
            int idx = _active.addindex(tick.symbol, true);

            // if we're not active, quit
            if (!_active[idx])
            {
                return;
            }
            // check for shutdown time
            if (tick.time > Shutdown)
            {
                // if so shutdown
                shutdown();
                // and quit
                return;
            }
            // apply bar tracking to all ticks that enter
            blt.newTick(tick);

            // ignore anything that is not a trade
            if (!tick.isTrade)
            {
                return;
            }

            // if we made it here, we have enough bars and we have a trade.

            // exits are processed first, lets see if we have our total profit
            if (Calc.OpenPL(tick.trade, pt[tick.symbol]) + pt[tick.symbol].ClosedPL > TotalProfitTarget)
            {
                // if we hit our target, shutdown trading on this symbol
                shutdown(tick.symbol);
                // don't process anything else after this (entries, etc)
                return;
            }
        }
Пример #16
0
        static GenericTracker <List <Token> > getstublessftable(GenericTracker <List <Token> > function2functoks)
        {
            var tmp        = function2functoks.ToArray();
            var stubtokens = new GenericTracker <List <Token> >(tmp.Length);

            for (int i = 0; i < tmp.Length; i++)
            {
                stubtokens.addindex(function2functoks.getlabel(i), function2functoks[i]);
            }
            // now process every function stub
            for (int i = 0; i < function2functoks.Count; i++)
            {
                // always pass in the stubs
                var stubless = getstublessfunction(i, stubtokens);
                // update the primary list with the stubless result
                function2functoks[i] = stubless;
            }
            return(function2functoks);
        }
Пример #17
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);
        }
        // GotTick is called everytime a new quote or trade occurs
        public override void GotTick(TradeLink.API.Tick tick)
        {
            // tmp workaround for "how to show debug messages from response constructor"
            if (debug_message_from_constructor.Length > 0)
            {
                D(debug_message_from_constructor);
                debug_message_from_constructor = "";
            }

            // keep track of time from tick
            time = tick.time;

            // safe tick to files
            //_ta.newTick(tick);

            // ignore quotes
            if (!tick.isTrade)
            {
                return;
            }

            // ignore ticks with timestamp prior to 9:30:00am
            if (tick.time < 93000)
            {
                return;
            }

            // ensure we track this symbol, all the other trackers will be indexed inside track_symbols_NewTxt()
            track_symbols.addindex(tick.symbol, false);

            // track tick
            track_ticks.newTick(tick);
            track_barlists.newTick(tick); // dimon: give any ticks (trades) to this symbol and tracker will create barlists automatically

            // if we don't have enough bars, wait for more ticks
            if (!track_barlists[tick.symbol].Has(_slow_ma_bar))
            {
                return;
            }
        }
Пример #19
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;
        }
Пример #20
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));
 }
Пример #21
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);
        }
        // GotTick is called everytime a new quote or trade occurs
        public override void GotTick(TradeLink.API.Tick tick)
        {
            // store tick
            tick_archiver.newTick(tick);
            return; // for now only track/store ticks here...

            // ignore quotes
            if (!tick.isTrade)
            {
                return;
            }

            // ensure we track this symbol, all the other trackers will be indexed inside track_symbols_NewTxt()
            track_symbols.addindex(tick.symbol, false);

            // track tick
            track_ticks.newTick(tick);

            // another "track tick" :)
            //
            // For now we track tick in 2 different trackers:
            // TickTracker
            // and
            // BarListTracker (connected with MessageTracker)
            //
            // todo: Read more on topic of TickTracker vs BarListTracker. And eventually get rid of one of them.
            //      TickTracker - seems have more functionality, but
            //      BarListTracker - can build bars with any interval (we can mix diff. bar size in one strategy easily using this!)
            //
            track_barlists.newTick(tick); // dimon: give any ticks (trades) to this symbol and tracker will create barlists automatically

            // if we don't have enough bars, wait for more ticks
            //if (!track_barlists[tick.symbol].Has(BarsBack)) return;

            // get current position
            Position pos = track_positions[tick.symbol];

            // if we're flat and haven't seen this symbol yet, then...
            if (pos.isFlat && !track_symbols[tick.symbol])
            {
                // strart tracking it (other trackers will be updated accordingly, see track_symbols_NewTxt()
                track_symbols[tick.symbol] = true;

                D(tick.symbol + ": entering long");
                O(new MarketOrder(tick.symbol, EntrySize));
            }
            else if (!pos.isFlat && !track_exitsignals[tick.symbol])
            {
                // get most recent tick data
                Tick k = track_ticks[tick.symbol];
                // estimate our exit price
                decimal exitprice = UseQuotes
                    ? (k.hasAsk && pos.isLong ? k.ask
                    : (k.hasBid && pos.isShort ? k.bid : 0))
                    : (k.isTrade ? k.trade : 0);
                // assuming we could estimate an exit, see if our exit would hit our target
                if ((exitprice != 0) && (Calc.OpenPT(exitprice, pos) > ProfitTarget))
                {
                    track_exitsignals[tick.symbol] = true;
                    D("hit profit target");
                    O(new MarketOrderFlat(pos));
                }
            }
            // --------------------------------------------
            //
            // this is a grey box that manages exits, so wait until we have a position
            //if (!pt[tick.symbol].isFlat) return;
            //
            //// calculate the MA from closing bars
            //decimal MA = Calc.Avg(Calc.Closes(track_barlists[tick.symbol], BarsBack));

            //// if we're short, a cross is when market moves above MA
            //// if we're long, cross is when market goes below MA
            //bool cross = pt[tick.symbol].isShort ? (tick.trade > MA) : (tick.trade < MA);

            //// if we have a cross, then flat us for the requested size
            //if (cross)
            //    sendorder(new MarketOrderFlat(pt[tick.symbol], exitpercent));

            //// notify gauntlet and kadina about our moving average and cross
            //sendindicators(new string[] { MA.ToString(), cross.ToString() });
            // --------------------------------------------
        }
Пример #23
0
 void gt_NewTxt2(string txt, int idx)
 {
     price1.addindex(txt, 0);
     price2.addindex(txt, 0);
     special.addindex(txt, true);
 }
Пример #24
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;

        }
Пример #25
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;
        }
        // GotTick is called everytime a new quote or trade occurs
        public override void GotTick(TradeLink.API.Tick tick)
        {
            base.GotTick(tick);

            // keep track of time from tick
            time = tick.time;

            // ignore quotes
            if (!tick.isTrade)
            {
                return;
            }

            // ignore ticks with timestamp prior to 9:30:00am
            if (tick.time < 93000)
            {
                return;
            }

            // --------------------------------------------------- rabbitmq begin -----------
            log_file.WriteLine(JsonConvert.SerializeObject(tick, Formatting.Indented));    // write all ticks into external file (to get a feeling on size)
            if (tick.time == 93205)
            {
                ;
            }
            if (false)
            {
                if (tick.time > 93000 && tick.time < 93500)
                {
                    string rabbit_serverAddress = "amqp://localhost/";
                    string rabbit_exchange      = "exch";
                    string rabbit_exchangeType  = "fanout";
                    string rabbit_routingKey    = "rout";
                    string rabbit_message       = JsonConvert.SerializeObject(tick, Formatting.Indented);

                    ConnectionFactory rabbit_cf = new ConnectionFactory();
                    rabbit_cf.Uri = rabbit_serverAddress;
                    IConnection rabbit_conn = rabbit_cf.CreateConnection();
                    IModel      rabbit_ch   = rabbit_conn.CreateModel();
                    rabbit_ch.ExchangeDeclare(rabbit_exchange, rabbit_exchangeType);
                    IBasicProperties msg_props = rabbit_ch.CreateBasicProperties();
                    msg_props.ContentType = "text/plain";
                    rabbit_ch.BasicPublish(rabbit_exchange,
                                           rabbit_routingKey,
                                           msg_props,
                                           Encoding.UTF8.GetBytes(rabbit_message));     // or Encoding.UTF8.GetBytes();  - we convert message into a byte array
                }
            }
            // --------------------------------------------------- rabbitmq end -----------

            // ensure we track this symbol, all the other trackers will be indexed inside track_symbols_NewTxt()
            track_symbols.addindex(tick.symbol, false);

            // track tick
            track_ticks.newTick(tick);

            // track (custom) bars
            track_barlists.newTick(tick); // dimon: give any ticks (trades) to this symbol and tracker will create barlists automatically

            // check if need to exit position:
            log_file.WriteLine("check if need to exit position: track_positions[tick.symbol].isLong=" + track_positions[tick.symbol].isLong.ToString());

            if (!track_positions[tick.symbol].isLong) // isFlat)        - we sell only if we have long positions
            {
                // should exit long position due to hit target?
                if (track_positions[tick.symbol].isLong)
                {
                    // time to exit long position?
                    bool should_exit = track_positions[tick.symbol].AvgPrice * (decimal)_target_price_k <= tick.trade;
                    if (should_exit)
                    {
                        string comment = "exit long position due to hit target";
                        sendorder(new SellMarket(tick.symbol, EntrySize, comment));
                        log_file.WriteLine("close position: " + comment);
                        return;
                    }
                }

                // should exit short position due to hit target?
                if (track_positions[tick.symbol].isShort)
                {
                    bool should_exit = track_positions[tick.symbol].AvgPrice * (decimal)_target_price_k >= tick.trade;
                    if (should_exit)
                    {
                        string comment = "exit short position due to hit target";
                        sendorder(new BuyMarket(tick.symbol, EntrySize, comment));
                        log_file.WriteLine("close position: " + comment);
                        return;
                    }
                }

                // should exit long position due to hit stop?
                if (track_positions[tick.symbol].isLong)
                {
                    bool should_exit = track_positions[tick.symbol].AvgPrice * (decimal)_stop_k >= tick.trade;
                    if (should_exit)
                    {
                        string comment = "exit long position due to hit stop";
                        sendorder(new SellMarket(tick.symbol, EntrySize, comment));
                        log_file.WriteLine("close position: " + comment);
                        return;
                    }
                }

                // should exit short position due to hit stop?
                if (track_positions[tick.symbol].isShort)
                {
                    bool should_exit = track_positions[tick.symbol].AvgPrice * (decimal)_target_price_k >= tick.trade;
                    if (should_exit)
                    {
                        string comment = "exit short position due to hit stop";
                        sendorder(new BuyMarket(tick.symbol, EntrySize, comment));
                        log_file.WriteLine("close position: " + comment);
                        return;
                    }
                }
            }
        }
Пример #27
0
 // link all the generic trackers together so we create
 // proper default values for each whenever we add symbol to one
 void _entrysignal_NewTxt(string txt, int idx)
 {
     _exitsignal.addindex(txt, false);
 }
Пример #28
0
 void MA_NewTxt(string txt, int idx)
 {
     // use a default lookback of 3
     LOOKBACK.addindex(txt, 3);
 }
Пример #29
0
        public static GenericTracker<Screener> fetchscreen(string url, DebugDelegate deb)
        {
            // get raw list
            string[][] raw = fetchrawlist(url,deb);
            debug("beginning screen indexing of "+raw.GetLength(0)+" screens.");
            GenericTracker<Screener> ss = new GenericTracker<Screener>(raw.GetLength(0), "SCREENS", new Screener());
            int l = 0;
            foreach (string[] r in raw)
            {
                l++;
                Screener s = getscreen_qdl(r);
                if (s.isValid)
                    ss.addindex(s.symbol, s);
                else
                {
/*
                    if (r!=null)
                        debug("ignoring invalid screen line#"+l.ToString("N0")+" with data: " + Util.join(r));
                    else
                        debug("ignoring invalid screen line#" + l.ToString("N0") + " with no data.");
 */
                }
            }
            debug("completed index of "+ss.Count+" screens.");
            return ss;

        }
Пример #30
0
 void indicatorcross1_NewTxt(string txt, int idx)
 {
     indicatorcross1.addindex(txt);
     indicatorcross2.addindex(txt);
     first1then2ok.addindex(txt);
 }
Пример #31
0
 void _active_NewTxt(string txt, int idx)
 {
     // go ahead and notify any other trackers about this symbol
     _wait.addindex(txt, false);
 }
Пример #32
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);
        }
Пример #33
0
 public static bool PlayHistoricalTicks(Response r, string symbol, int currentdate, int daysback, int expecteddays, DebugDelegate deb)
 {
     GenericTracker<string> symbols = new GenericTracker<string>();
     symbols.addindex(symbol, symbol);
     // calculate stop date
     DateTime stop = Util.ToDateTime(currentdate, 0);
     // calculate start date
     DateTime start = stop.Subtract(new TimeSpan(daysback, 0, 0, 0));
     // return results
     return PlayHistoricalTicks(r, symbols, start, stop, expecteddays, deb);
 }
Пример #34
0
        internal static GenericTracker <Token[]> getcodeconstants()
        {
            GenericTracker <Token[]> constname2consttoks = new GenericTracker <Token[]>();
            // keep track of block level
            int       blocklevel  = 0;
            const int classglobal = 2;

            // go through every token
            for (int i = 0; i < tokstream.Count; i++)
            {
                // get token
                var t = tokstream[i];
                // ignore quoted strings
                if (t.type == tokentype.quotedstring)
                {
                    continue;
                }
                // ignore new lines
                if (t.isLine)
                {
                    continue;
                }
                // count blocks
                if (t.type == tokentype.block_end)
                {
                    blocklevel--;
                }
                else if (t.type == tokentype.block_start)
                {
                    blocklevel++;
                }
                // only look for constants at class level
                if (blocklevel == classglobal)
                {
                    // ignore non symbols
                    if (!t.isSymbol)
                    {
                        continue;
                    }
                    // look for any constant
                    if (t.data != "const")
                    {
                        continue;
                    }
                    // ensure it's an access modifier
                    //if (ptok.data != "public")
                    //    continue;
                    // get next token for the name
                    var n = getnextsymbol(t, 2);
                    // ensure it's an assignment
                    if (!issymbolassignment(n))
                    {
                        continue;
                    }
                    // save tokens until the end of the constant
                    var ctoks = readtofirstof(t.id, tokentype.statement);
                    // save it
                    constname2consttoks.addindex(n.data, ctoks.ToArray());
                    // advance the pointer
                    i += (ctoks.Count - (i - t.id));
                    //var lasttoks = getlasttokens(i, 70);
                    //Console.WriteLine(n.ToString() + "\t" + lasttoks.Length);
                }
            }
            return(constname2consttoks);
        }
Пример #35
0
        public static GenericTracker<Screener> fetchscreen(string url, DebugDelegate deb)
        {
            // get raw list
            string[][] raw = fetchrawlist(url,deb);
            debug("beginning screen indexing of "+raw.GetLength(0)+" screens.");
            GenericTracker<Screener> ss = new GenericTracker<Screener>(raw.GetLength(0), "SCREENS", new Screener());
            foreach (string[] r in raw)
            {
                Screener s = getscreen(r);
                ss.addindex(s.symbol, s);
            }
            debug("completed index of "+ss.Count+" screens.");
            return ss;

        }
Пример #36
0
 void _orderid_NewTxt(string txt, int idx)
 {
     _kt.addindex(txt);
     _tickcounter.addindex(txt, 0);
 }