IABSocketAPI.pas

This sample shows an older version of the API. The latest API features are not shown here in this sample. The help file has a current list of all available methods, properties and events.

//************************************************************************** 
// 
//    IABSocketAPI - for use with InteractiveBrokers TradeWorkStation(TWS) 
//                   direct order placement API 
// 
//    by Ross Hemingway - iabsocketapi@hhssoftware.com 
// 
//    http://www.hhssoftware.com/iabsocketapi/ 
// 
//    This version is for use with TWS API v x.xx  (old api shown for demo purposes)

// 
// 
//************************************************************************** 
// 
//    For help with this API / component set - see the help file at the above site. 
//    Also see the readme.txt file attached in this zip package. 
// 
// 
//    This file has five classes defined.  Install just the TIABSocket into the library. 
//    The other objects compliment the TIABSocket component. 
// 
//************************************************************************** 
 
 
 
unit IABSocketAPI; 
 
interface 
 
uses SysUtils, Classes, ScktComp, Windows; 
 
const CLIENT_VERSION = 15; 
//  7 = 7.0,  8 = 7.01,  9 = 7.1 and 7.2, (9 had two releases from IAB), 
//  10 = 7.3, 
//  11 to 14 were NOT released to public by IAB. 
//  15 = 7.6       
(old api shown for demo purposes)
 
type 
  TIABAction = (iabIdle,iabBuy,iabSell,iabShort); 
  TIABConnection = (twsClosed,twsConnecting,twsReady,twsFailed); 
  TIABOrderOrigin = (orCustomer,orFirm,orUnknown); 
  TIABOrderState = (osPendSubmit,osPendCancel,osPreSubmit,osSubmitted,osCancelled,osFilled); 
  TIABOrderType = (otNoChange,otMarket,otLimit,otStop,otStopLimit,otRelative,otVWAP,otMarketClose,otLimitClose,otTrail,otLimitOpen,otMarketOpen,otOneCancelOther,otISEBlock,otUnknown); 
  TIABRight = (rtNone,rtPut,rtCall); 
  TIABSecurityType = (stStock,stOption,stFuture,stIndex,stFutOpt,stCash,stBag); 
  TIABTickType = (ttBidSize,ttBid,ttAsk,ttAskSize,ttLast,ttLastSize,ttHigh,ttLow,ttVolume,ttClose,ttNotSet); 
  TIABTimeInForce = (tifDay,tifGTC,tifIOC,tifOPG); 
  TIABOrderTypesSet = set of TIABOrderType; 
  TIABLegOpenClose = (locSamePos,locOpenPos,locClosePos,locUnknownPos);
  TIABExchangeStatus = (esUnknown,esAvailable,esUnAvailable);
  TIABActionFilter = (afNone,afBuy,afSell,afShort);
	
  TIABExecutionFilter = record
    ClientId: Integer;
    AccountCode: string;
    FromTime: TDateTime;
    Symbol: string;
    SecurityType: TIABSecurityType;
    Exchange: string;
    Action: TIABActionFilter;
  end;
  PTIABExecutionFilter = ^TIABExecutionFilter;
 
  TIABComboLeg = record 
    ContractId: Integer; 
    Action: TIABAction; 
    Ratio: Integer; 
    Exchange: string; 
    OpenClose: TIABLegOpenClose; 
  end; 
  PTIABComboLeg = ^TIABComboLeg; 
 
  TIABCodeMsgPair = record 
    Code: Integer; 
    Msg: string; 
  end; 
 
  TIABPortfolioItem = record 
    Symbol: string; 
    Local: string; 
    SecurityType: TIABSecurityType; 
    Expiry: string; 
    Strike: Double; 
    Right: TIABRight; 
    Currency: string; 
    Position: Integer; 
    MarketPrice: Double; 
    MarketValue: Double; 
    AverageCost: Double; 
    UnrealizedPNL: Double; 
    RealizedPNL: Double; 
  end; 
  PTIABPortfolioItem = ^TIABPortfolioItem; 
 
  TIABInstrumentSpecItem = record 
    MarketName: string; 
    TradingClass: string; 
    ContractId: Integer; 
    Multiplier: string; 
    MinimumTick: Double; 
    OrderTypes: TIABOrderTypesSet; 
    ValidExchanges: string; 
    Symbol: string; 
    SecurityType: TIABSecurityType; 
    Expiry: string; 
    Strike: Double; 
    Right: TIABRight; 
    Exchange: string; 
    Currency: string; 
    LocalSymbol: string; 
  end; 
  PTIABInstrumentSpecItem = ^TIABInstrumentSpecItem; 
 
  TIABExecution = record 
    ExecutionId: string; 
    Time: string; 
    AcctNumber: string; 
    Exchange: string; 
    Side: TIABAction; 
    Volume: Integer; 
    Price: Double; 
  end; 
  PTIABExecution = ^TIABExecution; 
 
  TIABPortfolio = class(TPersistent) 
  private 
    FList: TList; 
    function GetCount: Integer; 
    function GetItems(Index: Integer): TIABPortfolioItem; 
    procedure SetItems(Index: Integer; const Value: TIABPortfolioItem); 
  public 
    constructor Create; 
    destructor Destroy; override; 
    function Add(IABPortfolioItem: TIABPortfolioItem): Integer; 
    procedure Insert(Index: Integer; IABPortfolioItem: TIABPortfolioItem); 
    procedure Delete(Index: Integer); 
    function Find(IABPortfolioItem: TIABPortfolioItem): Integer; 
    property Count: Integer read GetCount; 
    property Items[Index: Integer]: TIABPortfolioItem read GetItems write SetItems; default; 
  end; 
 
  TIABInstrumentSpec = class(TPersistent) 
  private 
    FList: TList; 
    function GetCount: Integer; 
    function GetItems(Index: Integer): TIABInstrumentSpecItem; 
    procedure SetItems(Index: Integer; const Value: TIABInstrumentSpecItem); 
  public 
    constructor Create; 
    destructor Destroy; override; 
    function Add(IABInstrumentSpecItem: TIABInstrumentSpecItem): Integer; 
    procedure Insert(Index: Integer; IABInstrumentSpecItem: TIABInstrumentSpecItem); 
    procedure Delete(Index: Integer); 
    function Find(IABInstrumentSpecItem: TIABInstrumentSpecItem): Integer; 
    property Count: Integer read GetCount; 
    property Items[Index: Integer]: TIABInstrumentSpecItem read GetItems write SetItems; default; 
  end; 
 
  TIABOrder = class(TPersistent) 
  private 
    FAccount: string; 
    FAction: TIABAction; 
    FAuxPrice: Double; 
    FCurrency: string; 
    FExchange: string; 
    FExpiry: string; 
    FLocalSymbol: string; 
    FOCAgroup: string; 
    FOpenClose: Char; 
    FOrderOrigin: TIABOrderOrigin; 
    FOrderRef: string; 
    FOrderType: TIABOrderType; 
    FPrice: Double; 
    FQuantity: Integer; 
    FRight: TIABRight; 
    FSecurityType: TIABSecurityType; 
    FStrike: Double; 
    FSymbol: string; 
    FTimeInForce: TIABTimeInForce; 
    FTransmit: Boolean; 
    FCompleted: Boolean; 
    FTempId: Integer; 
    FPermId: Integer; 
    FFilled: Integer; 
    FRemaining: Integer; 
    FFillPrice: Double; 
    FLatestFillQty: Integer; 
    FLatestFillPrice: Double; 
    FChanged: Boolean; 
    FParentId: Integer; 
    FBlockOrder: Boolean; 
    FSweepToFill: Boolean; 
    FDisplaySize: Integer; 
    FTriggerMethod: Integer; 
    FExtendedHours: Boolean;
    FHidden: Boolean;
    FOnFill: TNotifyEvent; 
    FOnCompleted: TNotifyEvent; 
    FExecutions: array of TIABExecution;
    FComboLegs: array of TIABComboLeg; 
    FShareAllocation: string;
    FExternalOrder: Boolean;				 
    FClientId: Integer;
    FExternalOrder: Boolean;
    FDiscretAmount: Double;
    FGoodAfterTime: string;
    FFAdvGroup: string;
    FFAdvProfile: string;
    FFAdvMethod: string;
    FFAdvPercentage: string;		
    procedure SetExpiry(Value: string); 
    function GetExecutions(Index: Integer): TIABExecution; 
    procedure SetExecutions(Index: Integer; const Value: TIABExecution); 
    function GetExecutionsCount: Integer; 
    function GetComboLegs(Index: Integer): TIABComboLeg; 
    function GetComboLegsCount: Integer; 
    procedure SetComboLegs(Index: Integer; const Value: TIABComboLeg);		
  public 
    constructor Create; 
    destructor Destroy; override; 
    procedure Assign(Source: TPersistent); override;
    function AddComboLeg(ComboLeg: TIABComboLeg): Integer; 
    procedure DeleteComboLeg(Index: Integer); 
    property Changed: Boolean read FChanged write FChanged; 
    property Completed: Boolean read FCompleted write FCompleted; 
    property TempId: Integer read FTempId write FTempId; 
    property PermId: Integer read FPermId write FPermId; 
    property Filled: Integer read FFilled write FFilled; 
    property Remaining: Integer read FRemaining write FRemaining; 
    property FillPrice: Double read FFillPrice write FFillPrice; 
    property LatestFillQty: Integer read FLatestFillQty write FLatestFillQty; 
    property LatestFillPrice: Double read FLatestFillPrice write FLatestFillPrice; 
    property Executions[Index: Integer]: TIABExecution read GetExecutions write SetExecutions; 
    property ExecutionsCount: Integer read GetExecutionsCount; 
    property ComboLegs[Index: Integer]: TIABComboLeg read GetComboLegs write SetComboLegs; 
    property ComboLegsCount: Integer read GetComboLegsCount;
    property ShareAllocation: string read FShareAllocation write FShareAllocation;		 
    property ClientId: Integer read FClientId write FClientId; 
    property DiscretAmount: Double read FDiscretAmount write FDiscretAmount;
    property GoodAfterTime: string read FGoodAfterTime write FGoodAfterTime;
    property FAdvGroup: string read FFAdvGroup write FFAdvGroup;
    property FAdvProfile: string read FFAdvProfile write FFAdvProfile;
    property FAdvMethod: string read FFAdvMethod write FFAdvMethod;
    property FAdvPercentage: string read FFAdvPercentage write FFAdvPercentage;
    property OnFill: TNotifyEvent read FOnFill write FOnFill; 
    property OnCompleted: TNotifyEvent read FOnCompleted write FOnCompleted; 
  published 
    property Account: string read FAccount write FAccount; 
    property Action: TIABAction read FAction write FAction; 
    property AuxPrice: Double read FAuxPrice write FAuxPrice; 
    property Currency: string read FCurrency write FCurrency; 
    property Exchange: string read FExchange write FExchange; 
    property Expiry: string read FExpiry write SetExpiry; 
    property LocalSymbol: string read FLocalSymbol write FLocalSymbol; 
    property OCAGroup: string read FOCAgroup write FOCAgroup; 
    property OpenClose: Char read FOpenClose write FOpenClose default 'O'; 
    property OrderRef: string read FOrderRef write FOrderRef; 
    property OrderOrigin: TIABOrderOrigin read FOrderOrigin write FOrderOrigin; 
    property OrderType: TIABOrderType read FOrderType write FOrderType; 
    property Quantity: Integer read FQuantity write FQuantity; 
    property Price: Double read FPrice write FPrice; 
    property Right: TIABRight read FRight write FRight; 
    property SecurityType: TIABSecurityType read FSecurityType write FSecurityType; 
    property Strike: Double read FStrike write FStrike; 
    property Symbol: string read FSymbol write FSymbol; 
    property TimeInForce: TIABTimeInForce read FTimeInForce write FTimeInForce; 
    property Transmit: Boolean read FTransmit write FTransmit; 
    property ParentId: Integer read FParentId write FParentId; 
    property BlockOrder: Boolean read FBlockOrder write FBlockOrder; 
    property SweepToFill: Boolean read FSweepToFill write FSweepToFill; 
    property DisplaySize: Integer read FDisplaySize write FDisplaySize; 
    property TriggerMethod: Integer read FTriggerMethod write FTriggerMethod; 
    property ExtendedHours: Boolean read FExtendedHours write FExtendedHours;
    property Hidden: Boolean read FHidden write FHidden;
  end; 
 
  TIABOrders = class(TPersistent) 
  private 
    FList: TList; 
    function GetCount: Integer; 
    function GetItems(Index: Integer): TIABOrder; 
    procedure SetItems(Index: Integer; const Value: TIABOrder); 
  public 
    constructor Create; 
    destructor Destroy; override; 
    function Add(TempId, ClientId, PermId: Integer; IABOrder: TIABOrder): Integer; 
    procedure Insert(Index, TempId, ClientId, PermId: Integer; IABOrder: TIABOrder); 
    procedure Delete(Index: Integer); 
    function FindDuplicatePermIds(var Index1, Index2: Integer): Boolean; 
    function GetOrder(TempId, ClientId: Integer): TIABOrder;
    function IndexOfTempId(TempId, ClientId: Integer): Integer; 
    function IndexOfPermId(PermId: Integer): Integer; 
    function TempToPermId(TempId, ClientId: Integer): Integer; 
    procedure SetPermId(TempId, PermId: Integer); 
    property Count: Integer read GetCount; 
    property Items[Index: Integer]: TIABOrder read GetItems write SetItems; default; 
  end; 
 
  TIABAccountTime = procedure(Sender: TObject; TimeStamp: string) of object; 
  TIABAccountValue = procedure(Sender: TObject; Index: Integer) of object; 
  TIABConnectionState = procedure(Sender: TObject; State: TIABConnection) of object; 
  TIABError = procedure(Sender: TObject; TempId, ErrorCode: Integer; ErrorMsg: string) of object; 
  TIABOpenOrder = procedure(Sender: TObject; TempId: Integer; Order: TIABOrder) of object; 
  TIABOrderStatus = procedure(Sender: TObject; Order: TIABOrder; Status: TIABOrderState) of object; 
  TIABPortfolioUpdate = procedure(Sender: TObject; Index: Integer) of object; 
  TIABTickPrice = procedure(Sender: TObject; DataId: Integer; TickType: TIABTickType; Price: Double) of object; 
  TIABTickSize = procedure(Sender: TObject; DataId: Integer; TickType: TIABTickType; Size: Integer) of object; 
  TIABTickPriceAndSize = procedure(Sender: TObject; DataId: Integer; TickType: TIABTickType; Price: Double; Size: Integer) of object; 
  TIABInstrumentSpecDetails = procedure(Sender: TObject; Index: Integer) of object; 
  TIABExecutionEvent = procedure(Sender: TObject; Order: TIABOrder) of object; 
  TIABMarketDepthEvent = procedure(Sender: TObject; DataId, Index, Operation, Side, Size: Integer; Price: Double) of object; 
  TIABMarketLevel2Event = procedure(Sender: TObject; DataId, Index, Operation, Side, Size: Integer; Price: Double; MMId: string) of object; 
  TIABNewsBulletin = procedure(Sender: TObject; MsgID: Integer; Bulletin, NewsSource: string) of object;
  TIABExchangeStatusEvent = procedure(Sender: TObject; MsgID: Integer; Status: TIABExchangeStatus; Bulletin, NewsSource: string) of object;
  TIABManagedAccountsEvent = procedure(Sender: TObject; Details: string) of object;
	
  EIABSocket = class(Exception); 
  TIABSocket = class(TComponent) 
  private 
    FSocket: TClientSocket; 
    FConnected: Boolean; 
    FConnecting: Boolean; 
    FClientID: Integer; 
    FNextTempID: Integer; 
    FOrders: TIABOrders; 
    FReserveIds: Integer; 
    FDefaultOrder: TIABOrder; 
    FOutStream: TMemoryStream; 
    FInStream: TMemoryStream; 
    FOnAccountTime: TIABAccountTime; 
    FOnAccountValue: TIABAccountValue; 
    FOnConnectionState: TIABConnectionState; 
    FOnError: TIABError; 
    FOnOpenOrder: TIABOpenOrder; 
    FOnOrderStatus: TIABOrderStatus; 
    FOnPortfolioUpdate: TIABPortfolioUpdate; 
    FOnTickPrice: TIABTickPrice; 
    FOnTickSize: TIABTickSize; 
    FAccountValues: TStringList; 
    FPortfolio: TIABPortfolio; 
    FInstrumentSpecs: TIABInstrumentSpec; 
    FOnInstrumentSpecDetails: TIABInstrumentSpecDetails; 
    FMutex: THandle; 
    FOnEndOfStreamRead: TNotifyEvent; 
    FOnExecution: TIABExecutionEvent; 
    FOnMarketDepth: TIABMarketDepthEvent; 
    FOnMarketLevel2: TIABMarketLevel2Event; 
    FRebuildFromTWS: Boolean; 
    FOnRebuildFromTWS: TNotifyEvent; 
    FOnNewsBulletin: TIABNewsBulletin;
    FOnExchangeStatus: TIABExchangeStatusEvent;
    FOnManagedAccounts: TIABManagedAccountsEvent;	
    FOnTickPriceAndSize: TIABTickPriceAndSize;					
    procedure SetConnected(State: Boolean); 
    function GetConnected: Boolean; 
    function GetSocketPort: Integer; 
    procedure SetSocketPort(const Value: Integer); 
    function GetSocketHostAddress: string; 
    procedure SetSocketHostAddress(const Value: string); 
    procedure SetClientID(const Value: Integer); 
    procedure SetReserveIds(const Value: Integer); 
    procedure AddToOut(Value: string); overload; 
    procedure AddToOut(Value: Integer); overload; 
    procedure AddToOut(Value: Double); overload; 
    function GainSocketMutex: Boolean; 
    procedure SendToSocket(Id: Integer); 
    procedure SocketRead(Sender: TObject; Socket: TCustomWinSocket); 
    procedure SocketConnect(Sender: TObject; Socket: TCustomWinSocket); 
    procedure SocketDisconnect(Sender: TObject; Socket: TCustomWinSocket); 
    procedure SocketError(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer); 
    procedure Initialize; 
    function DeCodeData: Boolean; 
    procedure DoErrorEvent(TempId: Integer; Error: TIABCodeMsgPair); 
    procedure SendReserveId(Value: Integer); 
    function AmendOrderFill(TempId, Filled, Remaining: Integer; Price: Double): TIABOrder; 
    function AmendOrderCancel(TempId: Integer): TIABOrder; 
    function MatchExecToOrder(TempId: Integer; NewExec: TIABExecution): Integer; 
  public 
    constructor Create(Owner: TComponent); override; 
    destructor Destroy; override; 
    procedure CancelAccountUpdates;
    procedure CancelOrder(TempID: Integer); 
    procedure CancelMarketData(DataId: Integer); 
    procedure CancelMarketDepth(DataId: Integer); 
    procedure GetAccountUpdates(AccountCode: string); 
    procedure GetExecutions; 
    procedure GetInstrumentSpecs(Order: TIABOrder); 
    procedure GetMarketData(DataId: Integer; Order: TIABOrder); overload; 
    procedure GetMarketData(DataId: Integer; Symbol, Local, Exchange, Expiry, Currency: string; SecurityType: TIABSecurityType; Right: TIABRight; Strike: Double); overload; 
    procedure GetMarketDepth(DataId: Integer; Order: TIABOrder); overload; 
    procedure GetMarketDepth(DataId: Integer; Symbol, Local, Exchange, Expiry, Currency: string; SecurityType: TIABSecurityType; Right: TIABRight; Strike: Double); overload; 
    procedure GetOpenOrdersClient; 
    procedure GetOpenOrdersAccount; 
    procedure GetOpenOrdersTWS(AutoBind: Boolean); 
    function ModifyOrder(TempId, Quantity: Integer; OrderType: TIABOrderType; Price, AuxPrice: Double): Boolean; 
    function PlaceOrder(Order: TIABOrder): Integer; 
    procedure RebuildFromTWS;
    procedure GetNewsBulletins(AllMessages: Boolean);
    procedure CancelNewsBulletins;
    procedure SetServerLogLevel(LogLevel: Integer);		
    property Orders: TIABOrders read FOrders write FOrders; 
    property AccountValues: TStringList read FAccountValues; 
    property InstrumentSpecs: TIABInstrumentSpec read FInstrumentSpecs write FInstrumentSpecs; 
    property Portfolio: TIABPortfolio read FPortfolio write FPortfolio; 
    property OnEndOfStreamRead: TNotifyEvent read FOnEndOfStreamRead write FOnEndOfStreamRead; 
  published 
    property Connected: Boolean read GetConnected write SetConnected; 
    property ClientID: Integer read FClientID write SetClientID; 
    property DefOrder: TIABOrder read FDefaultOrder write FDefaultOrder; 
    property ReserveIDs: Integer read FReserveIds write SetReserveIds; 
    property TWSHostAddress: string read GetSocketHostAddress write SetSocketHostAddress; 
    property TWSPort: Integer read GetSocketPort write SetSocketPort default 7496; 
    property OnAccountTime: TIABAccountTime read FOnAccountTime write FOnAccountTime; 
    property OnAccountValue: TIABAccountValue read FOnAccountValue write FOnAccountValue; 
    property OnConnectionState: TIABConnectionState read FOnConnectionState write FOnConnectionState; 
    property OnError: TIABError read FOnError write FOnError; 
    property OnInstrumentSpecDetails: TIABInstrumentSpecDetails read FOnInstrumentSpecDetails write FOnInstrumentSpecDetails; 
    property OnOpenOrder: TIABOpenOrder read FOnOpenOrder write FOnOpenOrder; 
    property OnOrderStatus: TIABOrderStatus read FOnOrderStatus write FOnOrderStatus; 
    property OnPortfolioUpdate: TIABPortfolioUpdate read FOnPortfolioUpdate write FOnPortfolioUpdate; 
    property OnTickPrice: TIABTickPrice read FOnTickPrice write FOnTickPrice; 
    property OnTickSize: TIABTickSize read FOnTickSize write FOnTickSize; 
    property OnExecution: TIABExecutionEvent read FOnExecution write FOnExecution; 
    property OnMarketDepth: TIABMarketDepthEvent read FOnMarketDepth write FOnMarketDepth; 
    property OnMarketLevel2: TIABMarketLevel2Event read FOnMarketLevel2 write FOnMarketLevel2;
    property OnRebuildFromTWS: TNotifyEvent read FOnRebuildFromTWS write FOnRebuildFromTWS;
    property OnNewsBulletin: TIABNewsBulletin read FOnNewsBulletin write FOnNewsBulletin;
    property OnExchangeStatus: TIABExchangeStatusEvent read FOnExchangeStatus write FOnExchangeStatus;				 
    property OnManagedAccounts: TIABManagedAccountsEvent read FOnManagedAccounts write FOnManagedAccounts;
    property OnTickPriceAndSize: TIABTickPriceAndSize read FOnTickPriceAndSize write FOnTickPriceAndSize;
  end; 
 
  procedure Register; 
  function OrderTypeToStr(IABOrderType: TIABOrderType): string; 
 
const 
  OPERATION_INSERT = 0; 
  OPERATION_UPDATE = 1; 
  OPERATION_DELETE = 2; 
  SIDE_ASK = 0; 
  SIDE_BID = 1; 
 
implementation 
 
 ..............
 

... that is all I can show you.  From the above you can see what the unit is 
capable of.  To see the rest of the unit, you will need to purchase the API.

This sample shows an older version of the API.  The latest API features are not 
shown here in this sample.  The help file has a current list of all available 
methods, properties and events.

Any questions - just ask.

Regards

Ross Hemingway
iabsocketapi@hhssoftware.com