Monday, March 1, 2010

How to generate a Candlestick chart in FreeMAT or MATLAB

The plot below is generated in FreeMAT, it can also be run at MATLAB:








function gen_chart(D,O,H,L,C,symbol)
    %
    % This function generates a candlestick chart for a given O,H,L,C data
    % D is dates
    % O is open
    % H is high
    % L is low
    % C is close
    % symbol
    %
    % Example:
    % [D O H L C V]=get_symbol_data('F',150);
    % gen_chart(D,O,H,L,C,'F');
    %
    %
    %   Copyright 2010 EdgeMe
    %   $Revision: 1.0.0.0 $
    %   EdgeMe, 28-Feb-2010
    %
    %
    if nargin<6
        error('Not enough inputs');
    end



    datapoints=length(D);
    %make sure we have the same length of data
    if length(O) ~=datapoints || length(H) ~=datapoints || length(L) ~=datapoints ||length(C) ~=datapoints
        error('Data must be in the same length');
    end


    figure;


    hold on;
    %draw low to high lines
    for i=1:datapoints
        plot([i i],[L(i) H(i)],'Color','k');
        if C(i)>O(i)
            plot([i i],[O(i) C(i)],'linewidth',3,'color','g');
        else
            plot([i i],[O(i) C(i)],'linewidth',3,'color','r');
        end
    end


    title(symbol);
    hold off;
    grid on;

    %
    xlim([1 datapoints+1]);
    y=get(gca,'ylim');
    ymin=int16(y(1)-0.5);
    ymax=int16(y(2)+0.5);
    ylim([ymin ymax]);


    XTick=[];
    j=1;
    for i=1:10:datapoints
        XTick(j)=i;
        j=j+1;
    end

    %Set XTicklabel to an empty string
    set(gca,'XTick',XTick,'XTickLabel','')

    for i=1:length(XTick)
        % Set the new xTickLabels of Dates
        hText = text(XTick(i), double(ymin), D{XTick(i)});
        set(hText,'Rotation',28,'HorizontalAlignment','right');
    end

end

5 comments:

  1. Dear EdgeMe,

    I am new to matlab, am and in the process of switching over to freemat becos the pricing of matlab is ridiculous. I love your blog becos you use freemat code for the exact purpose I need: study of financial markets.

    I have a serious question. I have a live data feed into excel ( by dde or rtd), how do I transfer that live feed into freemat, so that I can chart and do analysis in realtime?

    ReplyDelete
  2. Good job! I like your post, it is very short but so informative and useful too.watch here

    ReplyDelete
  3. This article is an appealing wealth of informative data that is interesting and well-written. I commend your hard work on this and thank you for this information. You’ve got what it takes to get attention. how to read candlestick charts

    ReplyDelete
  4. Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. comparebrokers

    ReplyDelete
  5. Eyal Nachum is a fintech guru and a director at Bruc Bond. Eyal is the architect of the software that SMEs use to do cross-border payments.

    ReplyDelete