Пример #1
0
        static List <Token> getstublessfunction(int fidx, GenericTracker <List <Token> > stubs)
        {
            // get copy of the current stub
            var ftoks = new List <Token>(stubs[fidx]);
            // get this function's symbol
            var fsym = new string[] { stubs.getlabel(fidx) };
            // prepare a list of all symbols slurped into ftoken table
            var  syms = new List <string>(fsym);
            bool allsymbolsslurped = false;

            do
            {
                var lastsymcount = syms.Count;
                // look for all new symbols
                syms = getallsymbolspresent(ftoks.ToArray(), syms, stubs);
                // if found, slurp tokens and rerun until no new symbols' tokens are slurped
                for (int i = lastsymcount; i < syms.Count; i++)
                {
                    // get new symbol to slurp
                    var newfuncsym = syms[i];
                    // grab the tokens for this symbol
                    var newtoks = stubs[newfuncsym];
                    // slurp it into this function's implementation
                    ftoks.AddRange(newtoks);
                }
                // update continue state
                allsymbolsslurped = lastsymcount == syms.Count;
                // continue until all needed symbols are available in this substream
            } while (!allsymbolsslurped);
            return(ftoks);
        }
Пример #2
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));
        }
Пример #3
0
        /// <summary>
        /// populate generic tracker with most recent TA-lib result
        /// </summary>
        /// <param name="idx"></param>
        /// <param name="nb">number of elements (returned from ta lib)</param>
        /// <param name="dplaces">round to this many decimal places</param>
        /// <param name="res">result (returned from ta-lib)</param>
        /// <param name="gt"></param>
        /// <returns></returns>
        public static bool TAPopulateGT(int idx, int nb, int dplaces, ref double[] res, GenericTracker<decimal> gt)
        {
            if (nb <= 0) return false;
            gt[idx] = Math.Round(Convert.ToDecimal(res[nb - 1]), dplaces);
            return true;

        }
Пример #4
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);
        }
Пример #5
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;

            

            
        }
Пример #6
0
        public static bool GenRDTemplates(string outputtemplatefilename, string basenamespace, out string code, params string[] inputfiles)
        {
            code = string.Empty;
            // tokenize data
            bool tokok = true;

            for (int i = 0; i < inputfiles.Length; i++)
            {
                var source    = inputfiles[i];
                var inputcode = h.getfile(source, null);
                tokok &= createstream(source, inputcode, i == 0);
            }

            if (!tokok)
            {
                return(false);
            }

            // generate constants
            GenericTracker <Token[]> const2consttoks = getcodeconstants();

            // generate helpers

            GenericTracker <List <Token> > function2ftoks = new GenericTracker <List <Token> >();
            bool helperok = transform_assist_helpers(getallsourcetypes(basenamespace, inputfiles), const2consttoks, ref function2ftoks);


            // generate classes
            string        assistcode;
            List <string> typenames;
            var           assistok = transform_assist_calls(outputtemplatefilename, getsourcetype(basenamespace, inputfiles[0]),
                                                            function2ftoks, const2consttoks, out assistcode, out typenames);

            if (helperok && assistok)
            {
                // generate method to get all the types as params
                var getallmethod = gencode_gettypes_fromnames(outputtemplatefilename, typenames);

                // add to global RD listing class
                var rdlisting_class = TargetMap.GetClass(outputtemplatefilename, string.Empty, getallmethod);

                // wrap it all together
                code = RD_AssistTemplate.GetTemplateFile(rdlisting_class + assistcode);

                // save class if required
                bool savefile = !string.IsNullOrWhiteSpace(outputtemplatefilename);
                //var folder = h.gf();
                var folder = Environment.CurrentDirectory + "\\";
                var fn     = folder + outputtemplatefilename + ".cs";
                if (savefile && !string.IsNullOrWhiteSpace(code) && h.setfile(fn, code))
                {
                }


                return(true);
            }

            return(false);
        }
Пример #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);
        }
Пример #8
0
 /// <summary>
 /// provide the estimated # of symbols and the client to use
 /// </summary>
 /// <param name="tl"></param>
 /// <param name="estSymbols"></param>
 public SendorderTracker(TLClient tl, int estSymbols)
 {
     _tl = tl;
     _estsymcount = estSymbols;
     _ordersend.DoWork += new DoWorkEventHandler(_ordersend_DoWork);
     _loaded = new GenericTracker<bool>(estSymbols);
     _loaded.NewTxt += new TextIdxDelegate(_loaded_NewTxt);
     _resendq = new RingBuffer<Order>(estSymbols);
     _orderq = new RingBuffer<Order>(estSymbols);
     _retries = new GenericTracker<int>(estSymbols * 10);
 }
        // constructor always goes 1st
        public MegaResponseTemplate() : base()
        {
            // Custom name of response set by you
            Name = "MegaResponseTemplate";

            // track_symbols_NewTxt() called when new text label is added
            track_symbols.NewTxt += new TextIdxDelegate(track_symbols_NewTxt);

            //     Names of the indicators used by your response.  Length must correspond to
            //     actual indicator values send with SendIndicators event
            Indicators = GenericTracker.GetIndicatorNames(gens());

            track_barlists.GotNewBar += new SymBarIntervalDelegate(GotNewBar);
        }
Пример #10
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);
        }
Пример #11
0
        /// <summary>
        /// flat a symbol and flag it to allow prevention of future trading with status and supplied reason
        /// </summary>
        /// <param name="sym"></param>
        /// <param name="activesym"></param>
        /// <param name="_pt"></param>
        /// <param name="sendorder"></param>
        /// <param name="D"></param>
        /// <param name="reason"></param>
        public static void shutdown(string sym, GenericTracker <bool> activesym, PositionTracker _pt, OrderDelegate sendorder, DebugDelegate D, string reason)
        {
            if (!activesym[sym])
            {
                return;
            }
            Order o = new MarketOrderFlat(_pt[sym]);

            if (D != null)
            {
                string r = reason == string.Empty ? string.Empty : " (" + reason + ")";
                D("symbol shutdown" + r + ", flat order: " + o.ToString());
            }
            sendorder(o);
            activesym[sym] = false;
        }
Пример #12
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;
 }
Пример #13
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);
        }
Пример #14
0
/*
 *      // these variables "hold" the parameters set by the user above
 *      // also they are the defaults that show up first
 *      int _barsback = 2;
 *      BarInterval _barinterval = BarInterval.FiveMin;
 *      int _entrysize = 100;
 *      decimal _totalprofit = 200;
 *      int _shutdowntime = 155000;
 */

        void initialize()
        {
            // wait for fill
            _wait = new GenericTracker <bool>();
            // track whether shutdown
            _active = new GenericTracker <bool>();
            // hold last ma
            _sma = new GenericTracker <decimal>();

            // turn on bar tracking
            blt            = new BarListTracker(Interval);
            blt.GotNewBar += new SymBarIntervalDelegate(blt_GotNewBar);

            // turn on position tracking
            pt = new PositionTracker();
            // keep track of time for use in other functions
            time = 0;

            _active.NewTxt += new TextIdxDelegate(_active_NewTxt);
        }
Пример #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());
        }
Пример #16
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));
 }
Пример #17
0
        public void Importing()
        {
            const string FILE = "TestGenericTracker.txt";

            // setup mappings
            sym.NewTxt += new TextIdxDelegate(gt_NewTxt2);
            // import syms
            Assert.IsTrue(GenericTracker.CSVInitGeneric <bool>(FILE, ref sym, false));
            Assert.AreEqual(4, sym.Count);
            Assert.AreEqual(4, price1.Count);
            // import other col data
            Assert.IsTrue(GenericTracker.CSVCOL2Generic <decimal>(FILE, ref price1, 1));
            Assert.IsTrue(GenericTracker.CSVCOL2Generic <decimal>(FILE, ref price2, 3));
            Assert.IsTrue(GenericTracker.CSVCOL2Generic <bool>(FILE, ref special, 4));
            // check data
            Assert.AreEqual(10, price1["IBM"]);
            Assert.AreEqual(20, price2["IBM"]);
            Assert.AreEqual(1, price2["LVS"]);
            Assert.AreEqual(false, special["LVS"]);
            Assert.AreEqual(true, special["MHS"]);
            // verify FRX left alone
            Assert.AreEqual(true, special["FRX"]);
        }
Пример #18
0
 /// <summary>
 /// <summary>
 /// populate generic tracker with most recent TA-lib result
 /// </summary>
 /// <param name="idx"></param>
 /// <param name="nb">number of elements (returned from ta lib)</param>
 /// <param name="res">result (returned from ta-lib)</param>
 /// <param name="gt"></param>
 /// <returns></returns>
 public static bool TAPopulateGT(int idx, int nb, ref double[] res, GenericTracker<decimal> gt)
 {
     return TAPopulateGT(idx, nb, 2, ref res, gt);
 }
Пример #19
0
 /// <summary>
 /// flat a symbol and flag it to allow prevention of future trading with status
 /// </summary>
 /// <param name="sym"></param>
 /// <param name="activesym"></param>
 /// <param name="_pt"></param>
 /// <param name="sendorder"></param>
 /// <param name="D"></param>
 public static void shutdown(string sym, GenericTracker<bool> activesym, PositionTracker _pt, OrderDelegate sendorder, DebugDelegate D) { shutdown(sym, activesym, _pt, sendorder, D, string.Empty); }
Пример #20
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);
 }
Пример #21
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);
        }
Пример #22
0
 /// <summary>
 /// populate a gt with a talib integer result
 /// </summary>
 /// <param name="idx"></param>
 /// <param name="nb"></param>
 /// <param name="res"></param>
 /// <param name="gt"></param>
 /// <returns></returns>
 public static bool TAPopulateGT(int idx, int nb, ref int[] res, GenericTracker<int> gt) { return TAPopulateGT(idx, nb, 0, ref res, gt); }
Пример #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);
        }
Пример #24
0
        internal static bool transform_assist_calls(string groupname, string sourcetype, GenericTracker <List <Token> > symbolname2functiontoks, GenericTracker <Token[]> const2code, out string code, out List <string> typenames)
        {
            code = string.Empty;
            // get all assists in question
            var masterlist = AssistHelper.getavailableassists_names();
            var mastercopy = masterlist.ToArray();

            for (int i = 0; i < masterlist.Count; i++)
            {
                masterlist[i] = masterlist[i].Replace(sourcetype + ":", string.Empty);
            }
            // strip out their location

            int okcount = 0;
            int classes = 0;

            typenames = new List <string>();
            // process every primary source token
            for (int i = 0; i < primarytokencount; i++)
            {
                // get our building blocks
                var tok = tokstream[i];
                // see if we want it
                if (!tok.isSymbol)
                {
                    continue;
                }
                if (sourcetype.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 voidarguments = issymbolvoidargumentmethod(tok);
                var  masteridx     = masterlist.IndexOf(tok.data);
                bool userfacing    = (masteridx >= 0);
                bool hasname       = userfacing && (AssistHelper.getassist(mastercopy[masteridx], null).AssistName != "GleanCommon.Assist");
                // verify our current token is a void method that is user-facing
                if (voidarguments && userfacing && hasname)
                {
                    // get name
                    var fname = tok.data;
                    // get any helper code which might be called by our function
                    var helpercode = gethelpercode(fname, symbolname2functiontoks);
                    // get new class name (that will inherit from RD_AssistTemplate)
                    var classname = getclassname(fname);
                    // get the pretty name
                    var prettyname = GleanHelper.getsafevarname(AssistHelper.getassist(mastercopy[masteridx], null).AssistName);
                    // insert assist code RD class of the same name (eg GetOffsetTracker or taBollinger)
                    var classdefinition = RD_AssistTemplate.GetTemplateClass(classname, prettyname, "return " + fname + "();", helpercode, false, false);
                    code += classdefinition;
                    // count it
                    classes++;
                    okcount++;
                    typenames.Add(classname);
                }
            }



            return(true);
        }
Пример #25
0
 ///////////////////////////////////////////////////////////////////////
 // Initializers
 ///////////////////////////////////////////////////////////////////////
 public override void Reset()
 {
     Name = "MOC CloseTest";
     RequestedForSymbol = new GenericTracker<bool>();
 }
        string debug_message_from_constructor = ""; // need to store it and show on 1st tick, otherwise debug messages are wiped out when ticks start to arrive
        public _TS_step_by_step()
            : base()
        {
            System.Diagnostics.Debug.WriteLine("class _TS_step_by_step constructor entry point");
            string[] args = MyGlobals.args;     // extract main(args) from MyGlobals (we store main(args) in Kadina Program.cs, ASP, etc.)
            if (args == null)
            {
                throw new Exception("you forgot to set MyGlobals.args (in Kadina or asp or in whatever you use)");
            }

            string response_config = "";
            //string storage_service_config_jsonfile = "";
            string rabbitmq_config_jsonfile = "";

            var p = new OptionSet()
            {
                { "a|response-config=", "response json configuration file",
                  v => response_config = v },
                //{ "c|storage-service-config=", "path to storage_service json configuration file",
                //  v => storage_service_config_jsonfile = v},
                { "r|rabbitmq-config=", "path to rabbitmq json configuration file",
                  v => rabbitmq_config_jsonfile = v }
            };

            // parse  cmd-line args
            List <string> extra;

            try
            {
                extra = p.Parse(args);
            }
            catch (OptionException e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
                System.Diagnostics.Debug.WriteLine("Try `--help' for more information.");
                return;
            }

            // get settings from json file
            if (response_config != "")
            {
                response_parameters_holder = new ResponseParametersHolder();
                response_parameters_holder.parse_json_file(response_config);
                bson = response_parameters_holder.bson;

                //_ema_bar = Convert.ToInt32(bson["_ema_bar"]);
                _ema_bar            = BsonSerializer.Deserialize <int>(bson["_ema_bar"].ToJson());
                _response_barsize_s = BsonSerializer.Deserialize <int>(bson["_response_barsize_s"].ToJson());
                _stop_k             = BsonSerializer.Deserialize <double>(bson["_stop_k"].ToJson());
                _target_price_k     = BsonSerializer.Deserialize <double>(bson["_target_price_k"].ToJson());

                //_target_price_k = Convert.ToDouble(bson["_target_price_k"]);

                // Custom name of response set by you
                Name = BsonSerializer.Deserialize <string>(bson["name"].ToJson());

                //debug_message_from_constructor = "parsed json file - OK (set slow_ma=" + _slow_ma_bar + " fast_ma=" + _fast_ma_bar;
                //D(debug_message_from_constructor); // wtf? why this message never showed up? seems messages are cleaned right before 1st GotTick();

                //ResponseParametersHolder storage_service_parameters_holder = new ResponseParametersHolder();
                //storage_service_parameters_holder.parse_json_file(storage_service_config_jsonfile);
                //storage_service_parameters_bson = storage_service_parameters_holder.bson;

                ResponseParametersHolder rabbitmq_parameters_holder = new ResponseParametersHolder();
                rabbitmq_parameters_holder.parse_json_file(rabbitmq_config_jsonfile);
                rabbitmq_parameters_bson = rabbitmq_parameters_holder.bson;
                call_me_from_child_constructor();
            }


            // track_symbols_NewTxt() called when new text label is added
            track_symbols.NewTxt += new TextIdxDelegate(track_symbols_NewTxt);

            //     Names of the indicators used by your response.  Length must correspond to
            //     actual indicator values send with SendIndicators event
            Indicators = GenericTracker.GetIndicatorNames(gens());

            //[_response_barsize_s, 22]
            track_barlists            = new BarListTracker(new int[] { _response_barsize_s, 22 }, new BarInterval[] { BarInterval.CustomTime, BarInterval.CustomTime });
            track_barlists.GotNewBar += new SymBarIntervalDelegate(GotNewBar);
        }
 /// <summary>
 /// flat a symbol and flag it to allow prevention of future trading with status
 /// </summary>
 /// <param name="sym"></param>
 /// <param name="activesym"></param>
 /// <param name="_pt"></param>
 /// <param name="sendorder"></param>
 /// <param name="D"></param>
 public static void shutdown(string sym, GenericTracker<bool> activesym, PositionTracker _pt, OrderDelegate sendorder, DebugDelegate D) 
 {
     //send_event(MimeType.shutdown, "foo", "boo".ToJson());
     shutdown(sym, activesym, _pt, sendorder, D, string.Empty);
 }
        string debug_message_from_constructor = ""; // need to store it and show on 1st tick, otherwise debug messages are wiped out when ticks start to arrive
        public _SMA_Crossing_Response()
            : base()
        {
            string[] args = MyGlobals.args;

            bool   show_help       = false;
            string kadina_config   = "";
            string response_config = "";
            int    repeat          = 1;

            var p = new OptionSet()
            {
                { "k|kadina-config=", "response json configuration file",
                  v => kadina_config = v },
                { "r|response-config=", "response json configuration file",
                  v => response_config = v },
                { "z|zepeat=",
                  "the number of {TIMES} to repeat the greeting.\n" +
                  "this must be an integer.",
                  (int v) => repeat = v },
                { "v", "increase debug message verbosity",
                  v => { if (v != null)
                         {
                             ++verbosity;
                         }
                  } },
                { "h|help", "show this message and exit",
                  v => show_help = v != null },
            };

            List <string> extra;

            try
            {
                extra = p.Parse(args);
            }
            catch (OptionException e)
            {
                Console.Write("greet: ");
                Console.WriteLine(e.Message);
                Console.WriteLine("Try `greet --help' for more information.");
                return;
            }

            if (show_help)
            {
                ShowHelp(p);
                return;
            }



            // get settings from json file
            if (response_config != "")
            {
                response_parameters_holder = new ResponseParametersHolder();
                response_parameters_holder.parse_json_file(response_config);
                bson         = response_parameters_holder.bson;
                _slow_ma_bar = BsonSerializer.Deserialize <int>(bson["_slow_ma_bar"].ToJson());
                _fast_ma_bar = BsonSerializer.Deserialize <int>(bson["_fast_ma_bar"].ToJson());

                // Custom name of response set by you
                Name = BsonSerializer.Deserialize <string>(bson["name"].ToJson());

                debug_message_from_constructor = "parsed json file - OK (set slow_ma=" + _slow_ma_bar + " fast_ma=" + _fast_ma_bar;
                D(debug_message_from_constructor); // wtf? why this message never showed up? seems messages are cleaned right before 1st GotTick();
            }


            // track_symbols_NewTxt() called when new text label is added
            track_symbols.NewTxt += new TextIdxDelegate(track_symbols_NewTxt);

            //     Names of the indicators used by your response.  Length must correspond to
            //     actual indicator values send with SendIndicators event
            Indicators = GenericTracker.GetIndicatorNames(gens());

            track_barlists.GotNewBar += new SymBarIntervalDelegate(GotNewBar);
        }
Пример #29
0
 /// <summary>
 /// flat a symbol and flag it to allow prevention of future trading with status
 /// </summary>
 /// <param name="sym"></param>
 /// <param name="activesym"></param>
 /// <param name="_pt"></param>
 /// <param name="sendorder"></param>
 /// <param name="D"></param>
 public static void shutdown(string sym, GenericTracker <bool> activesym, PositionTracker _pt, OrderDelegate sendorder, DebugDelegate D)
 {
     shutdown(sym, activesym, _pt, sendorder, D, string.Empty);
 }
Пример #30
0
        /// <summary>
        /// populate a gt with a talib integer result
        /// </summary>
        /// <param name="idx"></param>
        /// <param name="nb"></param>
        /// <param name="dplaces"></param>
        /// <param name="res"></param>
        /// <param name="gt"></param>
        /// <returns></returns>
        public static bool TAPopulateGT(int idx, int nb, int dplaces, ref int[] res, GenericTracker<int> gt)
        {
            if (nb <= 0) return false;
            gt[idx] = res[nb - 1];
            return true;

        }
Пример #31
0
 public static decimal[] AbsoluteReturn(PositionTracker pt, GenericTracker<decimal> marketprices)
 {
     return AbsoluteReturn(pt, marketprices, true);
 }
Пример #32
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;

        }
Пример #33
0
 public static bool PlayHistoricalTicks(Response r, GenericTracker<string> symbols, int currentdate, int daysback, int expecteddays, DebugDelegate deb)
 {
     // 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
 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); }
        /// <summary>
        /// flat a symbol and flag it to allow prevention of future trading with status and supplied reason
        /// </summary>
        /// <param name="sym"></param>
        /// <param name="activesym"></param>
        /// <param name="_pt"></param>
        /// <param name="sendorder"></param>
        /// <param name="D"></param>
        /// <param name="reason"></param>
        public static void shutdown(string sym, GenericTracker<bool> activesym, PositionTracker _pt, OrderDelegate sendorder, DebugDelegate D, string reason)
        {
            //send_event(MimeType.shutdown, "foo", "boo".ToJson());

            if (!activesym[sym]) return;
            Order o = new MarketOrderFlat(_pt[sym]);
            if (D != null)
            {
                string r = reason == string.Empty ? string.Empty : " (" + reason + ")";
                D("symbol shutdown" + r + ", flat order: " + o.ToString());
            }
            sendorder(o);
            activesym[sym] = false;
        }
 public override void Reset()
 {
     RequestedForSymbol = new GenericTracker <bool>();
 }
Пример #37
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;

        }
Пример #38
0
 ///////////////////////////////////////////////////////////////////////
 // Initializers
 ///////////////////////////////////////////////////////////////////////
 public override void Reset()
 {
     Name = "MOC CloseTest";
     RequestedForSymbol = new GenericTracker <bool>();
 }
Пример #39
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;

        }
Пример #40
0
 public override void Reset()
 {
     RequestedForSymbol = new GenericTracker<bool>();
 }