Trade From Chart introduction

Trade from the chart (TFC) is a module that allows chart users to place trades directly from their charts. Users manipulate graphical tools with their mouse or fingers. Tools are available for placing market orders, limit and stop orders, and multi-leg orders. Unlike traditional "ticket" based online trading, users set their price level graphically and interactively in the context of the security. This is a quicker and more natural approach to trading.

**This module runs as a plug-in to the stx-advacned.html GUI interface and not as a stand-alone module, and will not work when running from the filesystem on Chrome, IE or Safari. Please either install files on a webserver or use Firefox for evaluation purposes.

This module requires the following files:

-stx-tfc.js -stx-tfc.css -stx-tfc.html

TFC is an optional feature not included in all packages.

User Interface

  • Market Order Widget - This widget provides a quick interface for users to enter market orders. A "buy" and "sell" button are available. This widget can be repositioned vertically by the user by grabbing and dragging it.

  • Buy/Sell/Short/Cover - This is the same widget in different configurations. Buy/Short will be available options if the user has no position in the security. If the user has a position then either Short/Cover or Sell/Buy will be available options, each of which will either increase or decrease the user's current position. Users drag the widget vertically to indicate the desired price to initiate the order. They may optionally then add stop and/or limit orders and position those orders graphically.

  • Spreads/Straddles/Brackets - These widgets automatically provide upper and lower bounds that the user can manipulate for creating these trading strategies.

    • Spread - A user can catch a momentum breakout in either direction.
    • Straddle - A user can catch sideways bounces off of support and resistance.
    • Bracket - A user can set "stop"/"take profit" levels on an existing open position

Note that many of these order types depend upon the availability of One Triggers the Other (OTO) and One Cancels the Other (OCO) order types in your firm's order management system (OMS). If your OMS cannot support OTO or OCO orders then these can be disabled with a simple configuration setting.

Open orders will appear on the screen as small arrow. These can be clicked or tapped to expose a cancel/modify dialog. Users can cancel an order simply by clicking the "cancel" button. They can modify the order simply by moving the graphical elements to new price levels.

Integration

To integrate TFC into your back end you should create a new class that is derived from the STX.Account base object (found in stx-tfc.js).

stx-tfc.js contains a 'Demo' instance of the STX.Account object called STX.Account.Demo. This demo object provides an example of a derived class that can be used as reference but should not be completely copied as it fictionally emulates order executions and automatically updates and open orders locally instead of taking new information from the back office.

You should derive your own class with interfaces to your server for the following functions:

Each time the TFC side-bar is opened, an new account is enabled, the positions view is changed, an order is placed, and order is cancelled, or the chart symbol is changed, STX.TFC#updateData will be called to refresh the account information on the screen.

Accounts can be enabled by calling STX.TFC#enableAccount which is automatically done when the TFC object is initially constructed in the STX.loadWidget() callback.

See STX.TFC and STX.Account for more details.

The following is an example of the required data format for the TFC Account object:

     this.currency="USD";
    this.balances={
        liquidity: 100000,
        unsettledCash: 0,
        cash: 100000,
        profitLoss: 0,
        buyingPower: 200000
    };
    this.positions={
        "IBM":{quantity:1000,basis:126.13, price:129.13, prevClose:123.13, currency:"USD"},
        "GE":{quantity:100,basis:26.11, price:24.11, prevClose:26.11, currency:"USD"},
        "SPY":{quantity:-1000,basis:187.11, price:187.11, prevClose:190.11, currency:"USD"},
        "LNKD":{quantity:-100,basis:230, price:186, prevClose:240, currency:"USD"}
    };
    this.openOrders={
        "IBM":[{id:"1", action:"sell", quantity:500, limit:197, tif:"GTC", currency:"USD"},
                {id:"2", action:"sell", quantity:500, limit:196, tif:"GTC", currency:"USD"}],
        "TSLA":[{id:"3", action:"buy", quantity:10, limit:170, tif:"DAY", currency:"USD"}],
        "GE":[{id:"4", action:"sell", quantity:100, limit:30, tif:"GTC", currency:"USD", oco:"5"},
                {id:"5", action:"sell", quantity:100, stop:25, tif:"GTC", currency:"USD", oco:"4"}
            ],
        "LNKD":[{id:"6", action:"buy", quantity:100, limit:112, tif:"DAY", currency:"USD", oto: [
                {id:"7", action:"sell", quantity:100, limit:130, tif:"GTC", currency:"USD", oco:"8"},
                {id:"8", action:"sell", quantity:100, stop:110, tif:"GTC", currency:"USD", oco:"7"}
                ]}
            ]
    };
    this.config={
        oto:true,
        oco:true,
        disableModifyOrderQuantity: false
    };

The following is an example of a fully functional balance fetch request using Ajax/JSON. Similar code can be derived to fetch all other Account components and place orders.

STX.Account.YourFeed.prototype.fetchBalances=function(cb){

    // make your server call here and in the request call back set balances and call cb();
    var self = this;
    STX.postAjax("http://jsfiddle.chartiq.com/sample_tfc_balances.js", null, function (status, myserverResponseData) {
        if (status != 200) {
            // something went wrong
            cb();
            return;
        }
        self.balances=JSON.parse(myserverResponseData);
        cb();
    });
};

Once your Account class is created and all fetching and order placing functions are fully functional, the TFC object should be constructed and associated with an STXChart (stx)object. It should also be passed a valid STX.Account which can be used for querying and placing orders. The TFC object creates and manages a number of DOM elements which are located in stx-tfc.html.

Code sample:

    stxx.account=new STX.Account.MyFeed();
    var tfcConfig={
        stx: stxx,
           account: stxx.account
    };
    stxx.tfc=new STX.TFC(tfcConfig);

If used within a Widget/Side Bar, you will also need to initialize the widget as follows:

STX.loadWidget("stx-tfc", function(err){

    // your widget handling code here
    // your TFC contructor here
}

Complete code for initializing the TFC object within a trading Widget can be found in stx-advacned.html. (search for "stx-tfc")

TFC will request updated information whenever the stock symbol is changed on the chart. It is not necessary to filter for that security. Simply pass all of the information related to that account.

When placing an order, your class should wait for a response from your server and then update open orders, balances and positions. After doing so it should then call the callback function that was passed in so that TFC knows to update the graphical elements on the screen.

Customization

TFC graphical components are plain html. As such they can be modified if desired. The JavaScript code for TFC references these objects by class name and expects the components to exist however it makes no restriction on how they look. You may apply CSS selectors to override color or layout. You may also add or remove HTML componentry. For instance if you require a disclaimer, simply add the disclaimer text to the HTML components.

STX.Account.config is an object that defines the behavior of TFC. You can turn off OTO orders by setting config.oto=false in your STX.Account derived class. Likewise set config.oco=false to disable OCO related functionality.

    this.config={
        oto:true,
        oco:true,
        disableModifyOrderQuantity: false
    };

Additional trading entitlements can be defined by modifying the STX.Account.Tradability function as needed.

The available flags are as:

  • tradable: true/false -- to enable or disable trading for the current symbol
  • shortable: true/false -- to enable or disable short trades for the current symbol
  • marketable: true/false -- to enable or disable market order for the current symbol

Localization will not translate the currency sign used to display money amounts, as this is not dependent on the location, but rather the currency of your data. All currencies are printed using the STX#money method, which can changed as needed based on the currency used at your back office. You can find this function in stx.js.

Including additional js files

Since the TFC plug in is dynamically loaded, including additional js files in the plug in must be done with care.

The best place to do this is on the STX.loadWidget callback function.

The following example outlines the process:

STX.loadWidget("plugins/tfc/stx-tfc", function(err){
    if(err){
        if(document.location.href.indexOf("file://")!=-1){
            alert("Some features such as Trade From Chart will not work when running from the filesystem on Chrome, IE or Safari. ")
        }
        return;
    }

    // now load your script using STX.loadScript, 
    // and have the rest of the original code loaded 
    // in the the STX.loadScript callback function 
    // so it all loads in order.

    STX.loadScript("yourScript.js", function(){

        // now load the rest of the original code

        stxx.account=new STX.Account.MyFeed();
        var tfcConfig={
            stx: stxx,
             account: stxx.account,
             loadPts: false   //set to true to load PTS
        };
        stxx.tfc=new STX.TFC(tfcConfig);
        // collapse/expand toggle button
        stxx.tfc.setResizeCallback(resizeScreen);
        stxx.tfc.selectSymbol=function(symbol){
              var symbol=symbol.toUpperCase();
              STXLoader(true);
              stxx.newChart(symbol, null, null, finishedLoadingNewChart(stxx.chart.symbol, symbol));
        };
        $$$("#btnToggleTrade").style.display="";
        attachSidePanelEvent($$$("#btnToggleTrade"), $$$(".stx-trade-panel"), function(opening){
            if(opening){
              stxx.tfc.openTFC();
            }else{
              stxx.tfc.closeTFC();
            }
        });
    });
});

FAQ

Q: Does the TFC module support multiple portfolios ?

A: Yes. You can create a menu that switches between accounts as needed; either to support brokers that work with many accounts or single users that have many portfolios. As the user selects a new account from the drop down, you will create an STX.Account object and associate it with the chart as outlined in the 'Integration' section above . Note that one account can be active for trading at any given time.

Q: Can the trading widget be forced to 'snap' to preset price intervals as it moves up and down the y axis?

A: Yes. By setting STXChart.YAxis#minimumPriceTick, you can force the widget so skip certain price values and instead 'snap' to your desired intervals. This will guarantee that an order is only placed at the allowed price intervals for the security in question.

Q: is there an interface for trading FOREX?

A: Yes. See the following tutorial: Trade From Chart - FOREX