예제 #1
0
        public void DefaultInt()
        {
            BarListTracker blt = new BarListTracker();

            blt.GotNewBar += new SymBarIntervalDelegate(blt_GotNewBar);

            Tick [] tape = TestBarList.SampleData();
            // get second tape and change symbol
            Tick[] tape2 = TestBarList.SampleData();
            for (int i = 0; i < tape2.Length; i++)
            {
                tape2[i].symbol = "TST2";
            }

            // add ticks from both tape to tracker
            for (int i = 0; i < tape.Length; i++)
            {
                blt.newTick(tape[i]);
                blt.newTick(tape2[i]);
            }

            //make sure we got two symbols as bar events
            Assert.AreEqual(2, syms.Count);
            // make sure our symbols matched barlist count
            Assert.AreEqual(blt.SymbolCount, syms.Count);

            int    secondcount = 0;
            string symstring   = string.Empty;

            foreach (string sym in blt)
            {
                secondcount++;
                symstring += sym;
            }

            // make sure enumeration equals symbol count
            Assert.AreEqual(syms.Count, secondcount);
            // make sure symbols are there
            Assert.IsTrue(symstring.Contains("TST") && symstring.Contains("TST2"));

            // change default interval
            blt.DefaultInterval = BarInterval.Minute;
            // make sure same on individual bars
            Assert.AreEqual(blt.DefaultInterval, blt["TST"].DefaultInterval);

            Assert.AreEqual(9, blt["TST"].IntervalCount(BarInterval.Minute));
            Assert.AreEqual(3, blt["TST"].IntervalCount(BarInterval.FiveMin));
        }
예제 #2
0
 public override void GotTick(Tick k)
 {
     // update offsets
     ot.newTick(k);
     // build bars from ticks
     blt.newTick(k);
 }
        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,这个数据是用不到的
            }
        }
예제 #4
0
        public override void GotTick(Tick tick)
        {
            // create bars from ticks
            _blt.newTick(tick);
            // make sure we have enough bars our indicator
            if (!_blt[tick.symbol].Has(MINBARS))
            {
                return;
            }
            // get highs from our bar
            decimal [] highs = _blt[tick.symbol].High();
            // get lows
            decimal [] lows = _blt[tick.symbol].Low();
            // compute high low ranges
            decimal [] hlrange = Calc.Subtract(highs, lows);
            // compute average range
            decimal avghl = Calc.Avg(hlrange);

            // debug it
            senddebug(avghl.ToString());
            // extra credit
            if (avghl > MAXVOL)
            {
                senddebug(tick.symbol + " exceeded max volatility " + tick.time);
            }
            // display it (gauntlet and kadina only)
            sendindicators(new string[] { tick.time.ToString(), avghl.ToString("N2") });
            // plot it (in kadina only)
            sendchartlabel(avghl + _blt[tick.symbol].RecentBar.Close, tick.time);
        }
예제 #5
0
        public override void  GotTick(Tick tick)
        {
            // enable bars for all ticks that come in
            blt.newTick(tick);

            // if we don't have one bar yet, wait for more ticks until continuing
            if (!blt[tick.symbol].Has(1))
            {
                return;
            }

            // get high
            decimal h = Calc.HH(blt[tick.symbol]);
            // get low
            decimal l = Calc.LL(blt[tick.symbol]);
            // get open
            decimal o = blt[tick.symbol][0].Open;

            // asymmetry calculations...

            // if there is no asymetry in this market, shutdown this response
            if (((h - o) > a) && ((o - l) > a))
            {
                isValid = false;
                return;
            }
            // if the range for the market is too small, wait
            if ((h - l) < r)
            {
                return;
            }
            // if the market gapped down after opening,
            // but now is turning around... go long
            if (((h - o) <= a) && ((h - tick.trade) > e))
            {
                sendorder(new BuyMarket(tick.symbol, EntrySize));
            }
            // if market gapped up after open,
            // but now is turning around to go negative... go short
            if (((o - l) <= a) && ((tick.trade - l) > e))
            {
                sendorder(new SellMarket(tick.symbol, EntrySize));
            }

            // get open pl in points
            decimal points = Calc.OpenPT(tick.trade, pt[tick.symbol]);

            // if we hit our profit or loss target, stop trading
            if ((points > p) || (points < s))
            {
                // flat us
                sendorder(new MarketOrderFlat(pt[tick.symbol]));
                // don't trade anymore
                isValid = false;
            }
        }
예제 #6
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;
        }
예제 #7
0
        public void TickInt()
        {
            Tick[]         tape = TestBarList.SampleData();
            BarListTracker blt  = new BarListTracker(new[] { 3 }, new BarInterval[] { BarInterval.CustomTicks });

            foreach (Tick k in tape)
            {
                blt.newTick(k);
            }

            Assert.AreEqual(4, blt[tape[0].symbol].Count);
        }
예제 #8
0
 public override void GotTick(Tick k)
 {
     // if we don't have bar data, request historical data
     if (_blt[k.symbol].Count == 0)
     {
         D(k.symbol + " no bars found, requesting...");
         sendmessage(MessageTypes.BARREQUEST, BarImpl.BuildBarRequest(k.symbol, BarInterval.Hour));
     }
     D(k.symbol + " bar count: " + _blt[k.symbol].Count);
     // update whatever data we have with ticks
     _blt.newTick(k);
 }
예제 #9
0
 public override void GotTick(Tick tick)
 {
     if (!isValid)
     {
         return;
     }
     if (!tick.isTrade)
     {
         return;
     }
     _time = tick.time;
     _barListTracker.newTick(tick);
 }
예제 #10
0
        public void AddIntraTicks()
        {
            SpoolIntraBars();

            Tick k = new TickImpl("SPY");

            k.ask   = 101;
            k.bid   = 100;
            k.date  = 20110208;
            k.trade = 100.5m;
            k.size  = 5000;
            int baseTime = 144500;

            for (int x = 0; x < 20; x++)
            {
                k.time = baseTime + x;
                intraBarTracker.newTick(k);
            }

            Assert.AreEqual(intraBarTracker["SPY"].RecentBar.Close, k.trade);
            DisplayTrackerContent(intraBarTracker["SPY"]);
        }
예제 #11
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;
            }
        }
예제 #12
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;
            }
        }
예제 #13
0
 public override void GotTick(Tick k)
 {
     // if we don't have bar data, request historical data
     if (_blt[k.symbol].Count == 0)
     {
         if (barRequestedFlag == 0)
         {
             D(k.symbol + " no bars found, requesting...");
             sendmessage(MessageTypes.BARREQUEST, BarImpl.BuildBarRequest(k.symbol, BarInterval.Day, 20120105));
             barRequestedFlag += 1;
         }
         else
         {
             D("Waiting for Broker backfill");
         }
     }
     D(k.symbol + " bar count: " + _blt[k.symbol].Count);
     // update whatever data we have with ticks
     _blt.newTick(k);
 }
        // 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;
            }
        }
예제 #15
0
        // GotTick is called everytime a new quote or trade occurs
        public override void  GotTick(Tick tick)
        {
            // make sure every tick has bars
            blt.newTick(tick);

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

            // if we don't have a trade, wait to calculate indicators here
            if (!tick.isTrade)
            {
                return;
            }

            // 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(blt[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() });
        }
예제 #16
0
        public override void GotTick(Tick tick)
        {
            // create bars from ticks
            _blt.newTick(tick);
            // make sure we have enough bars our indicator
            if (!_blt[tick.symbol].Has(MINBARS))
            {
                return;
            }
            // get highs from our bar
            decimal[] highs = _blt[tick.symbol].High();
            // get lows
            decimal[] lows = _blt[tick.symbol].Low();
            // compute high low ranges
            decimal[] hlrange = Calc.Subtract(highs, lows);
            // compute average range
            decimal avghl = Calc.Avg(hlrange);

            // ignore volatile symbols
            if (avghl > MAXVOL)
            {
                return;
            }
            // compute MA
            decimal ma = Calc.Avg(_blt[tick.symbol].Close());

            // trading rule
            if (_pt[tick.symbol].isFlat && (_blt[tick.symbol].RecentBar.Close > ma))
            {
                sendorder(new BuyMarket(tick.symbol, 100));
            }
            // exit rule
            if (_pt[tick.symbol].isLong && (_blt[tick.symbol].RecentBar.Close < ma))
            {
                sendorder(new MarketOrderFlat(_pt[tick.symbol]));
            }
        }
예제 #17
0
        // got tick is called whenever this strategy receives a tick
        public override void GotTick(Tick tick)
        {
            // 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, flat our position
                sendorder(new MarketOrderFlat(pt[tick.symbol]));
                // shut us down
                isValid = false;
                // don't process anything else after this (entries, etc)
                return;
            }
        }
예제 #18
0
 void h_GotTick(TradeLink.API.Tick t)
 {
     tickcount++;
     bt.newTick(t);
 }
예제 #19
0
 public override void GotTick(Tick k)
 {
     blt.newTick(k);
 }
        // 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() });
            // --------------------------------------------
        }
        // 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;
                    }
                }
            }
        }