% Sample Matlab callback for IB - used in conjunction with the IBMatlab function
%
% Usage examples:
%    IBMatlab(..., 'CallbackExecDetails',@IBMatlab_CallbackExecDetails)
%    IBMatlab(..., 'CallbackExecDetails',{@IBMatlab_CallbackExecDetails,extraData1,extraData2})
%
% See: http://www.interactivebrokers.com/php/apiUsersGuide/apiguide/java/java_ewrapper_methods.htm
% ^^^  http://www.interactivebrokers.com/php/apiUsersGuide/apiguide/java/execdetails.htm
%      http://www.interactivebrokers.com/php/apiguide/interoperability/activex_other/activexevents.htm#execDetails
function IBMatlab_CallbackExecDetails(hObject, eventData, varargin)  %#ok unused

    % Extract the basic event data components
    orderId       = eventData.orderId;   % This is normally -1: use eventData.execution.orderId instead
    orderId       = eventData.execution.orderId;

    contractData  = eventData.contract;
    executionData = eventData.execution;
    
    % Example of extracting data from the contract object:
    % See: http://www.interactivebrokers.com/php/apiUsersGuide/apiguide/java/contract.htm
    symbol  = contractData.symbol;
    secType = contractData.secType;
    % ... and several other contract data available - see the above webpage

    % Example of extracting data from the execution object:
    % http://www.interactivebrokers.com/php/apiUsersGuide/apiguide/java/execution.htm
    execId      = executionData.execId;
    time        = executionData.time;
    exchange    = executionData.exchange;
    side        = executionData.side;
    shares      = executionData.shares;
    price       = executionData.price;
    permId      = executionData.permId;
    liquidation = executionData.liquidation;
    cumQty      = executionData.cumQty;
    avgPrice    = executionData.avgPrice;
    % ... and several other contract data available - see the above webpage

    % Now do something useful with all this information... - let's store it in a CSV file:

    % First, Convert the data elements into a comma-separated string
    csvline = sprintf('%s,%d,%s,%d,%d,%f\n', time, orderId, symbol, ...
                                             shares, cumQty, price);

    % Now append this comma-separated string to the CSV file
    fid = fopen('executions.csv', 'at');  % 'at' = append text
    fprintf(fid, csvline);
    fclose(fid);

end  % IBMatlab_CallbackExecDetails
