Auto trading CL futures with Ninja and IB - NinjaTrader | futures io social day trading
futures io futures trading


Auto trading CL futures with Ninja and IB
Updated: Views / Replies:10,403 / 22
Created: by goforbroke01 Attachments:0

Welcome to futures io.

(If you already have an account, login at the top of the page)

futures io is the largest futures trading community on the planet, with over 90,000 members. At futures io, our goal has always been and always will be to create a friendly, positive, forward-thinking community where members can openly share and discuss everything the world of trading has to offer. The community is one of the friendliest you will find on any subject, with members going out of their way to help others. Some of the primary differences between futures io and other trading sites revolve around the standards of our community. Those standards include a code of conduct for our members, as well as extremely high standards that govern which partners we do business with, and which products or services we recommend to our members.

At futures io, our focus is on quality education. No hype, gimmicks, or secret sauce. The truth is: trading is hard. To succeed, you need to surround yourself with the right support system, educational content, and trading mentors Ė all of which you can find on futures io, utilizing our social trading environment.

With futures io, you can find honest trading reviews on brokers, trading rooms, indicator packages, trading strategies, and much more. Our trading review process is highly moderated to ensure that only genuine users are allowed, so you donít need to worry about fake reviews.

We are fundamentally different than most other trading sites:
  • We are here to help. Just let us know what you need.
  • We work extremely hard to keep things positive in our community.
  • We do not tolerate rude behavior, trolling, or vendors advertising in posts.
  • We firmly believe in and encourage sharing. The holy grail is within you, we can help you find it.
  • We expect our members to participate and become a part of the community. Help yourself by helping others.

You'll need to register in order to view the content of the threads and start contributing to our community.  It's free and simple.

-- Big Mike, Site Administrator

Reply
 
Thread Tools Search this Thread
 

Auto trading CL futures with Ninja and IB

  #1 (permalink)
VIP Member
Chicago
 
Futures Experience: Intermediate
Platform: NT
Broker/Data: IB
 
Posts: 11 since Jun 2009
Thanks: 8 given, 0 received

Auto trading CL futures with Ninja and IB

I've been manually trading with a very simple strategy and I converted it to trade automatically with NT and Interactive Brokers. That's when my problems started (apart from making money!). I posted on the NT forum: Automated strategy with Interactive Brokers and CL - Page 2 - NinjaTrader Support Forum and ended up at a dead end. Basically, when sending an order to IB for an energy future, where the contract expires during the month before the contract month, IB fills the order correctly and NT interprets the IB order execution and position messages as if an order had been filled for the prior month contract. As a result the strategy thinks it's flat, the chart is not updated and no strategy issued stop orders are acted upon.

Between NT and IB they have failed to fix this since at least April of this year and neither party can give me any idea of when it might be. So if I want to trade in this way I have to use an alternative to NT (with which I have, as have many, invested a massive amount of time) or change my broker.

The purpose of bringing this all up here is to see if anyone else has suffered this, and if so, how they got around it. It seems to me that the combination of NT auto strategy, IB and energy futures are not compatible. Are there any workarounds out there?

-thanks

Reply With Quote
 
  #2 (permalink)
Administrator: Retired Backtester
 Vendor: speedytradingservers.com 
Rennes France
 
Futures Experience: Advanced
Platform: NinjaTrader
Broker/Data: IB/Kinetick
Favorite Futures: Futures
 
sam028's Avatar
 
Posts: 3,366 since Jun 2009
Thanks: 3,573 given, 3,982 received

An interesting post about this issue, here.
If your entries/exit are simple, no scale-in/out, etc, there is maybe a solution...

Reply With Quote
 
  #3 (permalink)
VIP Member
Chicago
 
Futures Experience: Intermediate
Platform: NT
Broker/Data: IB
 
Posts: 11 since Jun 2009
Thanks: 8 given, 0 received


Sam028

Thanks for the reply. I have previously reviewed that thread and tried downgrading to TWS890 that was reported by a user as working. It didn't work and IB subsequently told me: "Unfortunately, the related change is within our server side. It is not feasible to fix this issue by downgrading to the 890 version of TWS. We have to provide a new API component in order to fix the issue."

Is this what you were referring to when you said there may be a solution?

-thanks

Reply With Quote
 
  #4 (permalink)
Administrator: Retired Backtester
 Vendor: speedytradingservers.com 
Rennes France
 
Futures Experience: Advanced
Platform: NinjaTrader
Broker/Data: IB/Kinetick
Favorite Futures: Futures
 
sam028's Avatar
 
Posts: 3,366 since Jun 2009
Thanks: 3,573 given, 3,982 received


goforbroke01 View Post
Sam028

Thanks for the reply. I have previously reviewed that thread and tried downgrading to TWS890 that was reported by a user as working. It didn't work and IB subsequently told me: "Unfortunately, the related change is within our server side. It is not feasible to fix this issue by downgrading to the 890 version of TWS. We have to provide a new API component in order to fix the issue."

Is this what you were referring to when you said there may be a solution?

-thanks

No. I think the solution might be something like:
- the strat is running with the simulation account, then:
-> a small program wrote in Java/C++ with the TWS API libraries read every x seconds the NT Access database, then send the order with the right contract to the TWS. I have a piece of Java code somewhere, which were doing something similar
or, maybe simple (and simple==reliable)
-> the strategy wrote in a text file what to do, then another simple Java/C++ (always with the TWS API lib) read this file every second, then send the real order to TWS.

But all these will only works with simple order management/simple money management, because NT will be lost, its position will be false, the truth will be in TWS only.

I'm testing this bug right now with TWS demo account and a basic strat, scary...


Last edited by sam028; September 6th, 2009 at 12:56 PM. Reason: typo
Reply With Quote
 
  #5 (permalink)
VIP Member
Chicago
 
Futures Experience: Intermediate
Platform: NT
Broker/Data: IB
 
Posts: 11 since Jun 2009
Thanks: 8 given, 0 received

Got it. Run NT and TWS separately with NT putting order information in a text file and a standalone program polling it and posting orders through the TWS API. I am an amateur programmer and will give it a try, maybe in C#. I will report back if I get it to work. I would welcome if you could share any of your success and/or challenges along the way. Thanks for your help.

-thanks

Reply With Quote
 
  #6 (permalink)
Administrator: Retired Backtester
 Vendor: speedytradingservers.com 
Rennes France
 
Futures Experience: Advanced
Platform: NinjaTrader
Broker/Data: IB/Kinetick
Favorite Futures: Futures
 
sam028's Avatar
 
Posts: 3,366 since Jun 2009
Thanks: 3,573 given, 3,982 received

Writing a basic text file within a strategy is quite easy in C#, there is an example in the official NT forum, here.
For reading this file, you can also have a look to trading-shim, which is made to talk with a TWS, and can read "orders" files. But I only played with it on Linux boxes, I'm not sure it can be run safely under Windows.
Anyway, the "reader" part might not be very hard to write in Java, there is some examples on how to use the TWS API, after reading the text file, it's something like:
 
Code
                            
...
            if (
contract_type.equals("FUT")){                
                
contract createContract(symbolcontract_typeexchange"USD");
            }
...                
            if (
order_type.equals("MKT"))
                
my_order createOrder(actionqty"MKT");
            if ( (
order_type.equals("LMT")) && (limit>0))
                
my_order createOrder(actionqty"LMT",limit);
....            
            
eClientSocket.placeOrder(ORDERIDcontractmy_order);
.... 

Reply With Quote
The following user says Thank You to sam028 for this post:
 
  #7 (permalink)
Just starting out...
Paris / France
 
Futures Experience: Intermediate
Platform: NT
Broker/Data: IB / ZF
Favorite Futures: FGBL, NQ
 
fle__'s Avatar
 
Posts: 21 since Sep 2009
Thanks: 2 given, 10 received

Hi,
have a look at this : Interactive Brokers C# Api | Dinosaur Technology and Trading
the c# could be the basis of your polling app, and there is only one programming language for your whole trading system. Its simpler.
Nt exports all executions in the "outgoing" directory, I remember that two files were involved. You will have to check yourself.

But there is more :
you can import all this interface source code to NT, compile, and run it directly from NT (from within a strat or an indic). You would place your code in the Onexecution().

Have fun.

Reply With Quote
The following 2 users say Thank You to fle__ for this post:
 
  #8 (permalink)
Administrator: Retired Backtester
 Vendor: speedytradingservers.com 
Rennes France
 
Futures Experience: Advanced
Platform: NinjaTrader
Broker/Data: IB/Kinetick
Favorite Futures: Futures
 
sam028's Avatar
 
Posts: 3,366 since Jun 2009
Thanks: 3,573 given, 3,982 received


fle__ View Post
Hi,
have a look at this : Interactive Brokers C# Api | Dinosaur Technology and Trading
the c# could be the basis of your polling app, and there is only one programming language for your whole trading system. Its simpler.
Nt exports all executions in the "outgoing" directory, I remember that two files were involved. You will have to check yourself.

But there is more :
you can import all this interface source code to NT, compile, and run it directly from NT (from within a strat or an indic). You would place your code in the Onexecution().

Have fun.

Wow, great link, powerful things can be done with this, without too much headaches. And not only for solving CL contract dates issue.
A strategy which is hedging stock trades with options looks possible now, and using IB combos, etc.

Reply With Quote
 
  #9 (permalink)
Just starting out...
Paris / France
 
Futures Experience: Intermediate
Platform: NT
Broker/Data: IB / ZF
Favorite Futures: FGBL, NQ
 
fle__'s Avatar
 
Posts: 21 since Sep 2009
Thanks: 2 given, 10 received

A small code as a starter

I can't export the strategy, so I just past the code :
I works on ES 1209

It has a problem : the system is SAR, so always in the market. If you don't match manually the strategy starting position with the account position, it does not work, because the first order of the strategy closes the current position (which does not exist if not entered manually) and then opens a new position in the opposite direction. Non SAR does not have this problem by starting the strategy when it is flat.

 
Code
// 
// Copyright (C) 2006, NinjaTrader LLC <www.ninjatrader.com>.
// NinjaTrader reserves the right to modify or overwrite this NinjaScript component with each release.
//

#region Using declarations
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Data;
using NinjaTrader.Indicator;
using NinjaTrader.Strategy;
using System.Collections.Generic;
using System.Text;
using Krs.Ats.IBNet;
using System.Threading;
using Krs.Ats.IBNet.Contracts;

#endregion

// This namespace holds all strategies and is required. Do not change it.
namespace NinjaTrader.Strategy
{
    /// <summary>
    /// Simple moving average cross over strategy.
    /// </summary>
    [Description("Simple moving average cross over strategy.")]
    public class _SampleIBinterface : Strategy
    {
        #region Variables
        private int        fast    = 5;
        private int        slow    = 10;
        
        private IOrder entryOrder = null;
        private static int NextOrderId = 0;
        private static Contract ES;
        private static Contract NQ;
        private static IBClient client;

        #endregion

        /// <summary>
        /// This method is used to configure the strategy and is called once before any strategy method is called.
        /// </summary>
        protected override void Initialize()
        {
            client = new IBClient();
            client.ThrowExceptions = true;

            client.TickPrice += client_TickPrice;
            client.TickSize += client_TickSize;
            client.Error += client_Error;
            client.NextValidId += client_NextValidId;
            client.UpdateMarketDepth += client_UpdateMktDepth;
            client.RealTimeBar += client_RealTimeBar;
            client.OrderStatus += client_OrderStatus;
            client.ExecDetails += new EventHandler<ExecDetailsEventArgs>(client_ExecDetails);
            ES = new Contract("ES", "GLOBEX", SecurityType.Future, "USD", "200912");

            
            SMA(Fast).Plots[0].Pen.Color = Color.Orange;
            SMA(Slow).Plots[0].Pen.Color = Color.Green;

            Add(SMA(Fast));
            Add(SMA(Slow));

            CalculateOnBarClose    = true;
        }

        /// <summary>
        /// Called on each bar update event (incoming tick).
        /// </summary>
        protected override void OnBarUpdate()
        {
            if (!client.Connected && !Historical) 
            {
                Print("Connecting to IB.");
                Trace.WriteLine("Connecting to IB.");
                client.Connect("127.0.0.1", 7496, ToTime(Time[0]));
            }
            else if(!Historical)
            {
                Print("Connected to IB.");
            }

            if (CrossAbove(SMA(Fast), SMA(Slow), 1))
                entryOrder = EnterLong();
            else if (CrossBelow(SMA(Fast), SMA(Slow), 1))
                entryOrder = EnterShort();
            
            if (entryOrder != null &&!Historical) Print("OnBarUpdate entryOrder "+entryOrder.ToString());
        }

        protected override void OnOrderUpdate(IOrder order)
        {
            if (entryOrder != null) Print("OnOrderUpdate Order "+entryOrder.ToString());
            else Print("OnOrderUpdate Order Nill");
            // Handle entry orders here. The entryOrder object allows us to identify that the order that is calling the OnOrderUpdate() method is the entry order.
            if (entryOrder != null && entryOrder.Token == order.Token)
            {    
                // Reset the entryOrder object to null if order was cancelled without any fill
                if (order.OrderState == NinjaTrader.Cbi.OrderState.Cancelled && order.Filled == 0)
                {
                    entryOrder = null;
                }
            }
        }

        
        protected override void OnExecution(IExecution execution) 
        { 
            Print("OnExecution Exec "+execution.ToString());

            if ((entryOrder != null && entryOrder.Token == execution.Order.Token) || execution.Order.Name == "Close position")
            {
                if (!Historical) 
                {
                    if (execution.Order.OrderState == NinjaTrader.Cbi.OrderState.Filled 
                        || execution.Order.OrderState == NinjaTrader.Cbi.OrderState.PartFilled 
                        || (execution.Order.OrderState == NinjaTrader.Cbi.OrderState.Cancelled && execution.Order.Filled > 0))
                    {
                        Krs.Ats.IBNet.Order TradedContractOrder = new Krs.Ats.IBNet.Order();
                        if (execution.MarketPosition==MarketPosition.Long)
                            TradedContractOrder.Action = ActionSide.Buy;
                        else
                            TradedContractOrder.Action = ActionSide.Sell;
                        TradedContractOrder.OutsideRth = false;
                        TradedContractOrder.OrderType = Krs.Ats.IBNet.OrderType.Market;
                        TradedContractOrder.TotalQuantity = execution.Quantity;
                        DateTime myTime = new DateTime();
                        myTime = DateTime.Now;
                        NextOrderId++;
                        client.PlaceOrder(NextOrderId, ES, TradedContractOrder);
                        
    //                    client.PlaceOrder(Convert.ToInt32(execution.Token), ES, TradedContractOrder);
                        Log("Exec "+execution.ToString(), NinjaTrader.Cbi.LogLevel.Information );
                        entryOrder     = null;
                    }
                
                    Print("OnExecution "+execution.ToString());
                }
            }
        }
        
        public override void Dispose() 
        { 
            // Clean up your resources here 
            // WILL BE A PROBLEM IF TWO CHART HAVE THE INDICATOR
                client.Disconnect();
                client.Dispose();
                Print("Disposing IB interface");            
            base.Dispose(); 
        }
        
        static void client_ExecDetails(object sender, ExecDetailsEventArgs e)
        {
            Console.WriteLine("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11}",
                e.Contract.Symbol, e.Execution.AccountNumber, e.Execution.ClientId, e.Execution.Exchange, e.Execution.ExecutionId,
                e.Execution.Liquidation, e.Execution.OrderId, e.Execution.PermId, e.Execution.Price, e.Execution.Shares, e.Execution.Side, e.Execution.Time);

            Console.WriteLine("IBExecDetails "+e.ToString());
        }

        static void client_RealTimeBar(object sender, RealTimeBarEventArgs e)
        {
            Console.WriteLine("Received Real Time Bar: " + e.Close);
            Trace.WriteLine("Received Real Time Bar: " + e.Close);
        }

        static void client_OrderStatus(object sender, Krs.Ats.IBNet.OrderStatusEventArgs e)
        {
            Console.WriteLine("Order Placed.");
            Console.WriteLine("Order Status"+e.ToString());
//            if (e.Status == OrderStatus.Canceled && order.Filled == 0)
//                {
//                    entryOrder = null;
//                }
        }

        static void client_UpdateMktDepth(object sender, UpdateMarketDepthEventArgs e)
        {
            Console.WriteLine("Tick ID: " + e.TickerId + " Tick Side: " + EnumDescConverter.GetEnumDescription(e.Side) +
                              " Tick Size: " + e.Size + " Tick Price: " + e.Price + " Tick Position: " + e.Position +
                              " Operation: " + EnumDescConverter.GetEnumDescription(e.Operation));
            Trace.WriteLine("Tick ID: " + e.TickerId + " Tick Side: " + EnumDescConverter.GetEnumDescription(e.Side) +
                              " Tick Size: " + e.Size + " Tick Price: " + e.Price + " Tick Position: " + e.Position +
                              " Operation: " + EnumDescConverter.GetEnumDescription(e.Operation));
        }

        static void client_NextValidId(object sender, NextValidIdEventArgs e)
        {
            Console.WriteLine("Next Valid Id: " + e.OrderId);
            NextOrderId = e.OrderId;
        }

        static void client_TickSize(object sender, TickSizeEventArgs e)
        {
            Console.WriteLine("Tick Size: " + e.Size + " Tick Type: " + EnumDescConverter.GetEnumDescription(e.TickType));
        }

        static void client_Error(object sender, ErrorEventArgs e)
        {
            Console.WriteLine("Error: "+ e.ErrorMsg);
            Trace.WriteLine("Error: "+ e.TickerId+ " "+ e.ErrorCode+ " "+ e.ErrorMsg);
        }

        static void client_TickPrice(object sender, TickPriceEventArgs e)
        {
            Console.WriteLine("Price: " + e.Price + " Tick Type: " + EnumDescConverter.GetEnumDescription(e.TickType));
        }


        #region Properties
        /// <summary>
        /// </summary>
        [Description("Period for fast MA")]
        [Category("Parameters")]
        public int Fast
        {
            get { return fast; }
            set { fast = Math.Max(1, value); }
        }

        /// <summary>
        /// </summary>
        [Description("Period for slow MA")]
        [Category("Parameters")]
        public int Slow
        {
            get { return slow; }
            set { slow = Math.Max(1, value); }
        }
        #endregion
    }
}

Reply With Quote
The following 2 users say Thank You to fle__ for this post:
 
  #10 (permalink)
Trading Apprentice
sarasota fl
 
Futures Experience: Intermediate
Platform: esignal ninja trader
Broker/Data: IB esignal
Favorite Futures: eur/usd
 
Posts: 39 since Dec 2009
Thanks: 30 given, 14 received


Dec 17 2009 I also have this same problem. I was doing fine then bang no stops entered. Ninja nor IB have of this date fixed the the problem. Has anyone ever recieved a notice from either IB or ninja that this might happen? I am looking for a credit since this is a known problem. Any one ever got a credit on this type of thing?

Reply With Quote

Reply



futures io > > > > Auto trading CL futures with Ninja and IB

Thread Tools Search this Thread
Search this Thread:

Advanced Search



Upcoming Webinars and Events (4:30PM ET unless noted)

Jigsaw Trading: TBA

Elite only

FuturesTrader71: TBA

Elite only

NinjaTrader: TBA

Jan 18

RandBots: TBA

Jan 23

GFF Brokers & CME Group: Futures & Bitcoin

Elite only

Adam Grimes: TBA

Elite only

Ran Aroussi: TBA

Elite only
     

Similar Threads
Thread Thread Starter Forum Replies Last Post
Trading CL (Crude Oil futures) #2 Big Mike Commodities Futures Trading 95 March 18th, 2015 08:13 PM
IB Trading Currency Futures Massive l Currency Futures 38 July 15th, 2011 12:30 PM
Auto futures trading on ThinkorSwim optionzen ThinkOrSwim Programming 6 June 3rd, 2011 04:36 PM
Futures -- ES vs. CL , HFT/algo trading josh The Elite Circle 1 January 27th, 2011 01:16 AM
Trading CL (Crude Oil Futures) tzachi Traders Hideout 145 September 4th, 2009 11:57 PM


All times are GMT -4. The time now is 06:54 PM.

Copyright © 2017 by futures io, s.a., Av Ricardo J. Alfaro, Century Tower, Panama, +507 833-9432, info@futures.io
All information is for educational use only and is not investment advice.
There is a substantial risk of loss in trading commodity futures, stocks, options and foreign exchange products. Past performance is not indicative of future results.
no new posts
Page generated 2017-12-13 in 0.14 seconds with 19 queries on phoenix via your IP 54.90.92.204