-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathC_BBG
More file actions
1770 lines (1604 loc) · 79.7 KB
/
C_BBG
File metadata and controls
1770 lines (1604 loc) · 79.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Option Explicit
' Works for reference Data, Bluk reference, Historical Data, and Positions from AIM services (Requires specific subscription)
' IMPORTANT: for AIM Services the code has not been tested - likely to not fully work!
' Data Returned is from (1,1) coordinates
' In the (0,x), or (x,0) there are usually Descriptive Fields (eg:Tickers, Field Names, Dates)
' This works in a Synchronous way, ie you do one request and have to wait for it to have returned data before doing another one
' For it to work you need to be logged in the Bloomberg Terminal and have the Bloomberg API for Excel installed
' To verify if you are logged in, in any Excel Cell type: =BDP("AAPL US Equity", "PX_LAST"), and it should return a price
' If it returns an error you are likely not logged in, or did not install the Excel API properly, or have reached the Max Data allowance.
' Check with a BBG rep for help
' You need have the Bloomberg VBA References Activated:
' ===> On top of here go to the "Tools" Menu, then "References...", find and have ticked: "Bloomberg API COM 3.5 Type Library"
' You can find Examples of usage in the code in the module: M_Examples_BBG
' Notes on Data limit:
' There is no explicit number Data Limit on Bloomberg, but there are two main limits:
' DAILY LIMIT: this is about requesting a very large amount of Tickers x Fields in a single Day (think in the 100s of thousands).
' MONTHLY LIMIT: this is about the diversity of Tickers X Fields in a given month, some fields have more cost than others (think in the 2k or less per month)
' Essentially you can hit the daily limit if you call the same Ticker x Field combo many times per day, you can hit the monthly limit if you request a
' lot of different things.
' If you hit either of these limits you might get some small and occasional extention from BBG, do a HelpHelp<GO>
' For Official Documentation/Downloads:
' Go to WAPI<GO> on your terminal (you very likely have a Desktop installation)
' Or online at: https://www.bloomberg.com/professional/support/api-library/
' DAPI<GO> also an excellent source on fields, and overview of what can be done
' Standard Services //blp/refdata:
' - ReferenceData: like BDP
' - PortfolioData: like BDS
' - HistoricalData: like BDH
' AIM Services //blp/tseapi & //blp/tsadf (Extra subscription required):
' - AIMPortfolioPositionsData UNTESTED
' - AIMHistPortfolioPositionsData UNTESTED
'
' For Subscriptions they are not available through this API due to VBA's limitations
'Constants
Private Const CONST_SERVICE_TYPE_REF As String = "//blp/refdata"
Private Const CONST_SERVICE_TYPE_PRT As String = "//blp/tseapi" ' For AIM Services
Private Const CONST_SERVICE_TYPE_HPRT As String = "//blp/tsadf" ' For AIM Services
Private Const CONST_REQUEST_TYPE_REFERENCE As String = "ReferenceDataRequest"
Private Const CONST_REQUEST_TYPE_PORT As String = "PortfolioDataRequest"
Private Const CONST_REQUEST_TYPE_HISTORICAL As String = "HistoricalDataRequest"
Private Const CONST_REQUEST_TYPE_PORTFOLIO As String = "EapiRequestPosition"
Private Const CONST_REQUEST_TYPE_HIST_PORT As String = "RequestPositionHistory"
Private Const CONST_DEBUG_PRINT_MSG As Boolean = False ' If True will Print the MSGs in the Debug (For Debuging)
Private Const CONST_VERSION As String = "1.1.0"
'Private data structures
Private bInputSecurityArray() As String
Private bInputFieldArray() As String
Private bOutputArray As Variant
Private bOverrideFieldArray() As String
Private bOverrideValueArray() As Variant
Private bSetErrorMessageToEmpty As Boolean
'Session Objects
Private bSession As blpapicomLib2.Session
Private bSessionOptions As blpapicomLib2.SessionOptions
Private bService As blpapicomLib2.Service
Private bRequest As blpapicomLib2.REQUEST
Private bEvent As blpapicomLib2.Event
'Request Data Objects
Private bRequestType As String
Private bSecurities() As String
Private bNumSecurities As Integer
Private bFields() As String
Private bNumFields As Integer
Private bStartDate As String
Private bEndDate As String
Private bPx As Integer
Private bErrorType As String
Private bentityType As String
Private bentityName As String
'Overrides Data Objects
Private bOverrides As Element
Private bOverrideFields() As String
Private bOverrideValues() As Variant
Private bcalendarCodeOverride As String
Private bcalendarOverridesOperation As String
Private bcurrencyCode As String
Private bnonTradingDayFillOption As String
Private bnonTradingDayFillMethod As String
Private bperiodicityAdjustment As String
Private bperiodicitySelection As String
Private bmaxDataPoints As Long
Private bpricingOption As String
Private bincludeCash As Boolean
Private bReferenceDate As String
Private Sub Class_Initialize()
' Attempt to Open the Session
Call OpenSession
End Sub
Private Sub Class_Terminate()
' Cleaning up or Terminate the Class without crashing Excel (in case Terminate did not trigger)
' Also cleans up the Session object
Call Terminate
On Error Resume Next
bSession.Stop
On Error GoTo 0
Set bSession = Nothing
End Sub
Public Property Get Version() As String
Version = CONST_VERSION
End Property
' =========================
' === SUPPORT FUNCTIONS ===
' =========================
Private Sub Terminate()
' Cleans up the objects
Set bOutputArray = Nothing
Set bEvent = Nothing
Set bRequest = Nothing
Set bService = Nothing
End Sub
Private Function FlattenArray(ByVal InputArray As Variant) As Variant
' Converts inputs to a 1D Array, including Ranges, and single values
' Limited to 2D arrays (while Excel has a limit of 60D)
Dim FlatArray As Variant
Dim i As Long, j As Long, Counter As Long
Dim NumRows As Long, NumCols As Long
If TypeName(InputArray) = "Range" Then
' Range input
NumRows = InputArray.Rows.Count
NumCols = InputArray.Columns.Count
ReDim FlatArray(1 To (NumRows * NumCols))
Counter = 1
For i = 1 To NumRows
For j = 1 To NumCols
FlatArray(Counter) = InputArray(i, j)
Counter = Counter + 1
Next j
Next i
ElseIf IsArray(InputArray) = True Then
Dim NumDim As Integer
On Error Resume Next
For i = 1 To 60
NumDim = LBound(InputArray, i)
If Err.Number <> 0 Then Exit For
Next i
On Error GoTo 0
Select Case NumDim
Case 1
' 1D Array, keeping it as is
FlatArray = InputArray
Case 2
' 2D Array, will flatten it under the NumRows * NumCols principle
NumRows = LBound(InputArray, 1) + UBound(InputArray, 1) - 1
NumCols = LBound(InputArray, 2) + UBound(InputArray, 2) - 1
ReDim FlatArray(1 To (NumRows * NumCols))
Counter = 1
For i = 1 To NumRows
For j = 1 To NumCols
FlatArray(Counter) = InputArray(i, j)
Counter = Counter + 1
Next j
Next i
FlattenArray = FlatArray
Case Else
Err.Raise vbObjectError, "C_BBG.FlattenArray", "The Array you want to flatten has more than 2 dimentions: " & NumDim
End Select
Else
' Not an Array we convert it to a 1,1
ReDim FlatArray(1 To 1)
FlatArray(1) = InputArray
End If
FlattenArray = FlatArray
End Function
Private Function ConvertDateToBloomberg(DblDate As Date) As String
' Converts a normal Date to a bloomberg formated Date
' a string of format YYYYMMDD
Dim D As Integer, M As Integer, Y As Integer
D = Day(DblDate): M = Month(DblDate): Y = Year(DblDate)
If D < 10 And M < 10 Then
ConvertDateToBloomberg = Y & "0" & M & "0" & D
ElseIf D < 10 Then
ConvertDateToBloomberg = Y & M & "0" & D
ElseIf M < 10 Then
ConvertDateToBloomberg = Y & "0" & M & D
Else
ConvertDateToBloomberg = Y & M & D
End If
End Function
Private Function Sanitise_String(SomeString As Variant) As String
' Will Sanitise for VBA an input string by removing illegal characters
' Excel VBA only Supports ASCII Codes from 0 to 255, otherwise they are replaced by the 63 for "?"
Dim i As Integer
For i = 1 To Len(SomeString)
If Asc(Mid(SomeString, i, 1)) = 63 Then
If i = 1 Then
SomeString = Right(SomeString, Len(SomeString) - 1)
i = i - 1
ElseIf i = Len(SomeString) Then
SomeString = Left(SomeString, Len(SomeString) - 1)
Else
SomeString = Left(SomeString, i - 1) & Right(SomeString, Len(SomeString) - i)
i = i - 1
End If
End If
Next i
Sanitise_String = SomeString
End Function
Private Function Aggregate_Ticker_Field(Ticker As String, Field As String) As String
' Aggregates the Ticker and Field into a single string
' Seperation Character :, can be modified to any character or combination
Aggregate_Ticker_Field = Ticker & ":" & Field
End Function
' =========================
' === REQUEST FUNCTIONS ===
' =========================
Public Function ReferenceData(ByVal Tickers As Variant, _
ByVal Fields As Variant, _
Optional ByVal OverrideFields As Variant, _
Optional ByVal OverrideValues As Variant, _
Optional ByVal SetErrorMessagesToEmpty As Boolean = False) As Variant
'Gets the Reference Data, BDP Equivalent
' Inputs:
' Can be arrays or ranges of any dimention, eg: 2*2 Tickers input would be converted to a 4 long single array for processing
' - Tickers(): an array of BBG Tickers: eg: "AAPL US Equity" or "GT10 Govt"
' - Fields(): an array of BBG Fields: eg: "PX_LAST", "CRNCY", etc... you can find them under FLDS<GO>
' - OverrideFields(): an array of override Fields, some fields can be overriden, check FLDS<GO>, select a field and check bottom of the screen
' - OverrideValues(): the value to override the Fields
' - SetErrorMessagesToEmpty(): If True, will convert non-request breaking errors (eg: a field that does not apply to a Ticker such as Duration for an Equity)
' to an empty entry in the returned data table, if set to False (Default) will return the error code provided by BBG
' Output:
' - An Array with data in the 1,1 to x,x, and in the 0 coordinates are the name of the Fields and Tickers
Dim i As Integer
'1. Take the Mandatory Data
Dim ServiceType As String
bRequestType = CONST_REQUEST_TYPE_REFERENCE ' By Definition
ServiceType = CONST_SERVICE_TYPE_REF ' By Definition
' 1.1 Verify Ticker Inputs
Dim NumTickers As Long, NumValidTickers As Long
Tickers = FlattenArray(Tickers)
NumTickers = LBound(Tickers, 1) + UBound(Tickers, 1) - 1
For i = 1 To NumTickers
If Tickers(LBound(Tickers, 1) + i - 1) <> "" Then
' A Ticker is Valid if non-empty
' Sending empty string Tickers will crash the application
NumValidTickers = NumValidTickers + 1
If NumValidTickers = 1 Then
ReDim bSecurities(1 To NumValidTickers)
Else
ReDim Preserve bSecurities(1 To NumValidTickers)
End If
bSecurities(NumValidTickers) = Tickers(LBound(Tickers, 1) + i - 1)
End If
Next i
If NumValidTickers = 0 Then
Err.Raise vbObjectError, "C_BBG.ReferenceData", "There are no non-empty Tickers provided!"
Exit Function
Else
bNumSecurities = NumValidTickers
End If
' 1.2 Verify Fields Inputs
Dim NumFields As Long, NumValidFields As Long, FlatFields() As Variant
Fields = FlattenArray(Fields)
NumFields = LBound(Fields, 1) + UBound(Fields, 1) - 1
For i = 1 To NumFields
If Fields(LBound(Fields, 1) + i - 1) <> "" Then
' A Field is Valid if non-empty string
' Sending an empty string field will crash the application
NumValidFields = NumValidFields + 1
If NumValidFields = 1 Then
ReDim bFields(1 To NumValidFields)
Else
ReDim Preserve bFields(1 To NumValidFields)
End If
bFields(NumValidFields) = Fields(LBound(Fields, 1) + i - 1)
End If
Next i
If NumValidFields = 0 Then
Err.Raise vbObjectError, "C_BBG.ReferenceData", "There are no non-empty Fields provided!"
Exit Function
Else
bNumFields = NumValidFields
End If
'2. Take and Verify the Optional Data
Dim NumOvFields As Integer, NumOvValues As Integer, NumValidOvFieldsValues As Integer
If IsMissing(OverrideFields) = False Then
OverrideFields = FlattenArray(OverrideFields)
If IsMissing(OverrideValues) = True Then
Err.Raise vbObjectError, "C_BBG.ReferenceData", "You have provided OverrideFields, but not OverrideValues!"
Exit Function
Else
' Both overrideFields and overrideValues are provided, check they are the same size and have all non-empty inputs
OverrideValues = FlattenArray(OverrideValues)
NumOvFields = LBound(OverrideFields, 1) + UBound(OverrideFields, 1) - 1
NumOvValues = LBound(OverrideValues, 1) + UBound(OverrideValues, 1) - 1
ReDim bOverrideFields(1 To NumOvFields), bOverrideValues(1 To NumOvValues)
For i = 1 To NumOvFields
' Note that we check for pairs of non-empty Field, Value, if either is empty both are skipped
If OverrideFields(LBound(OverrideFields, 1) + i - 1) <> "" And OverrideValues(LBound(OverrideValues, 1) + i - 1) <> "" Then
NumValidOvFieldsValues = NumValidOvFieldsValues + 1
bOverrideFields(NumValidOvFieldsValues) = OverrideFields(LBound(OverrideFields, 1) + i - 1)
If IsDate(OverrideValues(LBound(OverrideValues, 1) + i - 1)) = True Then
' If we have a date override we have to convert it to the BBG format
bOverrideValues(NumValidOvFieldsValues) = ConvertDateToBloomberg(CDate(OverrideValues(LBound(OverrideValues, 1) + i - 1)))
Else
bOverrideValues(NumValidOvFieldsValues) = OverrideValues(LBound(OverrideValues, 1) + i - 1)
End If
End If
Next i
End If
ElseIf IsMissing(OverrideValues) = False Then
Err.Raise vbObjectError, "C_BBG.ReferenceData", "You have provided OverrideValues, but not OverrideFields!"
Exit Function
End If
' 2.1 Set the ErrorMessage Policy
bSetErrorMessageToEmpty = SetErrorMessagesToEmpty
'3. Pre-Generate the Output Array/Matrix
ReDim bOutputArray(0 To bNumSecurities, 0 To bNumFields)
For i = 1 To bNumFields
bOutputArray(0, i) = bFields(i)
Next i
For i = 1 To bNumSecurities
bOutputArray(i, 0) = bSecurities(i)
Next i
' 4. Open the Service
Dim HaveService As Boolean
HaveService = OpenService(ServiceType)
If HaveService = False Then
' Terminate early, return Empty, the error message has already been raised
Exit Function
End If
'5. Generate Request
Dim override As blpapicomLib2.Element
Set bRequest = bService.CreateRequest(bRequestType)
For i = 1 To NumValidTickers
bRequest.GetElement("securities").AppendValue bSecurities(i)
Next i
For i = 1 To NumValidFields
bRequest.GetElement("fields").AppendValue bFields(i)
Next i
If NumValidOvFieldsValues > 0 Then
Set bOverrides = bRequest.GetElement("overrides")
For i = 1 To NumValidOvFieldsValues
Set override = bOverrides.AppendElment()
override.SetElement "fieldId", bOverrideFields(i)
override.SetElement "value", bOverrideValues(i)
Next i
End If
' 6. Send the Request
Dim RequestId As blpapicomLib2.CorrelationId
On Error Resume Next
Set RequestId = bSession.SendRequest(bRequest)
'RequestId = bSession.SendRequest(bRequest)
If Err.Number <> 0 Then
Err.Raise vbObjectError, "C_BBG.ReferenceData", "Error: Could not send the Request, check that you have provided correct inputs!"
Exit Function
End If
On Error GoTo 0
' 7. Process the Incoming BBG Events
Call catchServerEvent
' 8. Return the Data and clean-up
ReferenceData = bOutputArray
Call Terminate
End Function
Public Function PortfolioData(ByVal Tickers As Variant, _
ByVal Fields As Variant, _
Optional ByVal ReferenceDate As Variant, _
Optional ByVal OverrideFields As Variant, _
Optional ByVal OverrideValues As Variant, _
Optional ByVal SetErrorMessagesToEmpty As Boolean = False) As Variant
'Gets the Portfolio Data, BDS Equivalent
' Inputs:
' Can be arrays or ranges of any dimention, eg: 2*2 Tickers input would be converted to a 4 long single array for processing
' - Tickers: one or a list of Portoflio Tiuckers
' - Fields: a single Field: possibles: PORTFOLIO_MWEIGHT, PORTFOLIO_MEMBERS, PORTFOLIO_MPOSITION, PORTFOLIO_DATA
' - ReferenceDate: Targets the Positions of the portfolio for a Specific Date
' - OverrideFields(): an array of override Fields, some fields can be overriden, check FLDS<GO>, select a field and check bottom of the screen
' - OverrideValues(): the value to override the Fields
' - SetErrorMessagesToEmpty(): If True, will convert non-request breaking errors (eg: a field that does not apply to a Ticker such as Duration for an Equity)
' to an empty entry in the returned data table, if set to False (Default) will return the error code
' Output:
' - An Array with data in the 1,1 to x,x, and in the 0 coordinates are the name of the Fields and the Name of the Portfolio
Dim i As Long, j As Long, k As Integer, l As Integer
'1. Take the Mandatory Data
Dim ServiceType As String
bRequestType = CONST_REQUEST_TYPE_PORT ' By Definition
ServiceType = CONST_SERVICE_TYPE_REF ' By Definition
' 1.1 Verify Ticker Inputs
Dim NumTickers As Long, NumValidTickers As Long
Tickers = FlattenArray(Tickers)
NumTickers = LBound(Tickers, 1) + UBound(Tickers, 1) - 1
For i = 1 To NumTickers
If Tickers(LBound(Tickers, 1) + i - 1) <> "" Then
' A Ticker is Valid if non-empty
' Sending empty string Tickers will crash the application
NumValidTickers = NumValidTickers + 1
If NumValidTickers = 1 Then
ReDim bSecurities(1 To NumValidTickers)
Else
ReDim Preserve bSecurities(1 To NumValidTickers)
End If
bSecurities(NumValidTickers) = Tickers(LBound(Tickers, 1) + i - 1)
End If
Next i
If NumValidTickers = 0 Then
Err.Raise vbObjectError, "C_BBG.PortfolioData", "There are no non-empty Tickers provided!"
Exit Function
'ElseIf NumValidTickers > 1 Then
' Err.Raise vbObjectError, "C_BBG.PortfolioData", "There is more than 1 Portfolio Ticker provided!"
Else
bNumSecurities = NumValidTickers
End If
' 1.2 Verify Fields Inputs
Dim NumFields As Long, NumValidFields As Long, FlatFields() As Variant
Fields = FlattenArray(Fields)
NumFields = LBound(Fields, 1) + UBound(Fields, 1) - 1
For i = 1 To NumFields
If Fields(LBound(Fields, 1) + i - 1) <> "" Then
' A Field is Valid if non-empty string
' Sending an empty string field will crash the application
NumValidFields = NumValidFields + 1
If NumValidFields = 1 Then
ReDim bFields(1 To NumValidFields)
Else
ReDim Preserve bFields(1 To NumValidFields)
End If
bFields(NumValidFields) = Fields(LBound(Fields, 1) + i - 1)
End If
Next i
If NumValidFields = 0 Then
Err.Raise vbObjectError, "C_BBG.PortfolioData", "There are no non-empty Fields provided!"
Exit Function
ElseIf NumValidFields > 1 Then
Err.Raise vbObjectError, "C_BBG.PortfolioData", "There is more than 1 Portfolio Field provided!"
Else
bNumFields = NumValidFields
End If
'2. Take and Verify the Optional Data
Dim NumOvFields As Integer, NumOvValues As Integer, NumValidOvFieldsValues As Integer
If IsMissing(OverrideFields) = False Or IsMissing(OverrideValues) = False Or IsMissing(ReferenceDate) = False Then
' We have some overrides
If IsMissing(OverrideValues) <> IsMissing(OverrideFields) Then
' There is an issue with the optional overrides
Err.Raise vbObjectError, "C_BBG.PortfolioData", "You have either provided OverrideFields and no OverrideValues or the opposite, you must provide both!"
Exit Function
ElseIf IsMissing(OverrideValues) = True Then
' Skip
Else
' Extract the Extra Overrides
OverrideFields = FlattenArray(OverrideFields)
OverrideValues = FlattenArray(OverrideValues)
NumOvFields = LBound(OverrideFields, 1) + UBound(OverrideFields, 1) - 1
NumOvValues = LBound(OverrideValues, 1) + UBound(OverrideValues, 1) - 1
ReDim bOverrideFields(1 To NumOvFields), bOverrideValues(1 To NumOvValues)
For i = 1 To NumOvFields
' Note that we check for pairs of non-empty Field, Value, if either is empty both are skipped
If OverrideFields(LBound(OverrideFields, 1) + i - 1) <> "" And OverrideValues(LBound(OverrideValues, 1) + i - 1) <> "" Then
NumValidOvFieldsValues = NumValidOvFieldsValues + 1
bOverrideFields(NumValidOvFieldsValues) = OverrideFields(LBound(OverrideFields, 1) + i - 1)
If IsDate(OverrideValues(LBound(OverrideValues, 1) + i - 1)) = True Then
' If we have a date override we have to convert it to the BBG format
bOverrideValues(NumValidOvFieldsValues) = ConvertDateToBloomberg(CDate(OverrideValues(LBound(OverrideValues, 1) + i - 1)))
Else
bOverrideValues(NumValidOvFieldsValues) = OverrideValues(LBound(OverrideValues, 1) + i - 1)
End If
End If
Next i
End If
If IsMissing(ReferenceDate) = False Then
' We add that to the bOverrideFields and bOverrideValues
NumValidOvFieldsValues = NumValidOvFieldsValues + 1
If NumValidOvFieldsValues > 1 Then
ReDim Preserve bOverrideFields(1 To NumValidOvFieldsValues), bOverrideValues(1 To NumValidOvFieldsValues)
Else
ReDim bOverrideFields(1 To NumValidOvFieldsValues), bOverrideValues(1 To NumValidOvFieldsValues)
End If
bOverrideFields(NumValidOvFieldsValues) = "REFERENCE_DATE"
bOverrideValues(NumValidOvFieldsValues) = ConvertDateToBloomberg(CDate(ReferenceDate))
End If
End If
' 2.1 Set the ErrorMessage Policy
bSetErrorMessageToEmpty = SetErrorMessagesToEmpty
'3. Generate the Output Array/Matrix
' Initialize it at 0,0 as we are going to increase its size as we receive messages from BBG
ReDim bOutputArray(0 To 0)
' 4. Open the Service
Dim HaveService As Boolean
HaveService = OpenService(ServiceType)
If HaveService = False Then
' Terminate early, return Empty, the error message has already been raised
Exit Function
End If
'5. Generate Request
Dim override As blpapicomLib2.Element
Set bRequest = bService.CreateRequest(bRequestType)
For i = 1 To NumValidTickers
bRequest.GetElement("securities").AppendValue bSecurities(i)
Next i
For i = 1 To NumValidFields
bRequest.GetElement("fields").AppendValue bFields(i)
Next i
If NumValidOvFieldsValues > 0 Then
Set bOverrides = bRequest.GetElement("overrides")
For i = 1 To NumValidOvFieldsValues
Set override = bOverrides.AppendElment()
override.SetElement "fieldId", bOverrideFields(i)
override.SetElement "value", bOverrideValues(i)
Next i
End If
' 6. Send the Request
Dim RequestId As blpapicomLib2.CorrelationId
On Error Resume Next
Set RequestId = bSession.SendRequest(bRequest)
'RequestId = bSession.SendRequest(bRequest)
If Err.Number <> 0 Then
Err.Raise vbObjectError, "C_BBG.PortfolioData", "Error: Could not send the Request, check that you have provided correct inputs!"
Exit Function
End If
On Error GoTo 0
' 7. Process the Incoming BBG Events
Call catchServerEvent
' 8. Post Processing of the bOutputArray
Dim NumDatas As Integer, NumObs As Long, Cols() As String, NumCols As Integer, Counter As Long, OutData() As Variant
' 8.1 Get the Number of Rows and Columns in total
For i = 1 To UBound(bOutputArray, 1)
NumDatas = NumDatas + UBound(bOutputArray(i), 1)
If NumCols = 0 Then
NumCols = UBound(bOutputArray(i), 2)
ReDim Cols(1 To NumCols)
For j = 1 To UBound(bOutputArray(i), 2)
Cols(j) = bOutputArray(i)(0, j)
Next j
Else
For j = 1 To UBound(bOutputArray(i), 2)
For k = 1 To NumCols
If bOutputArray(i)(0, j) = Cols(k) Then
' The Column already exists we move on to the next
Exit For
End If
If k = NumCols Then
NumCols = NumCols + 1
ReDim Preserve Cols(1 To NumCols)
Cols(NumCols) = bOutputArray(i)(0, j)
End If
Next k
Next j
End If
Next i
' 8.2 Define and Populate the OutData
ReDim OutData(0 To NumDatas, 0 To NumCols)
For i = 1 To NumCols
OutData(0, i) = Cols(i)
Next i
Counter = 0
For i = 1 To UBound(bOutputArray, 1)
' Populate the Portfolio Name
For l = 1 To UBound(bOutputArray(i), 1)
OutData(Counter + l, 0) = bOutputArray(i)(0, 0)
Next l
For j = 1 To UBound(bOutputArray(i), 2)
For k = 1 To NumCols
If Cols(k) = bOutputArray(i)(0, j) Then
' Matched the Columns
' Now populate the rows of this column
For l = 1 To UBound(bOutputArray(i), 1)
OutData(Counter + l, k) = bOutputArray(i)(l, j)
Next l
Exit For ' Matched the Columns, moving to the next column
End If
Next k
Next j
' Shift the counter to the next entry
Counter = Counter + UBound(bOutputArray(i), 1)
Next i
' 9. Return the Data and clean-up
PortfolioData = OutData
Call Terminate
End Function
Public Function HistoricalData(ByVal Tickers As Variant, _
ByVal Fields As Variant, _
ByVal startDate As Date, _
ByVal endDate As Date, _
Optional OrderDescending As Boolean = True, _
Optional ByVal calendarCodeOverride As Variant, _
Optional ByVal calendarOverridesOperation As Variant, _
Optional ByVal currencyCode As Variant, _
Optional ByVal nonTradingDayFillOption As Variant, _
Optional ByVal nonTradingDayFillMethod As Variant, _
Optional ByVal periodicityAdjustment As Variant, _
Optional ByVal periodicitySelection As Variant, _
Optional ByVal maxDataPoints As Variant, _
Optional ByVal pricingOption As Variant, _
Optional ByVal OverrideFields As Variant, _
Optional ByVal OverrideValues As Variant, _
Optional ByVal SetErrorMessagesToEmpty As Boolean = False) As Variant
'Gets Historical Data, like BDH
' Inputs:
' Can be arrays or ranges of any dimention, eg: 2*2 Tickers input would be converted to a 4 long single array for processing
' - Tickers(): an array of BBG Tickers: eg: "AAPL US Equity" or "GT10 Govt"
' - Fields(): an array of BBG Fields: eg: "PX_LAST", "CRNCY", etc... you can find them under FLDS<GO>
' - StartDate: a Date Type value for the Oldest Date
' - EndDate: a Date Type value for the Newest Date
' - OrderDescending: if True, the Dates of the returned data will be ordered in Descending (Most recent Date will have the smallest Index, ie top of the table)
' - calendarCodeOverride: look for Calendar Codes at CDR<GO>
' - calendarOverridesOperations: works with Calendar Code Override: can be CDR_AND or CDR_OR
' - currencyCode: the ISO3 Currency Code
' - nonTradingDayFillOption: one of these: NON_TRADING_WEEKDAYS;ALL_CALENDAR_DAYS;ACTIVE_DAYS_ONLY
' - nonTradingDayFillMethod: one of these: PREVIOUS_VALUE;NIL_VALUE
' - periodicityAdjustment: one of these: ACTUAL;CALENDAR;FISCAL
' - periodicitySelection: one of these: DAILY;WEEKLY;MONTHLY;QUARTERLY;SEMI_ANNUALLY;YEARLY
' - maxDataPoints: Max of data you want returned
' - pricingOption: one of these: PRINCING_OPTION_PRICE;PRICING_OPTION_YIELD
' - OverrideFields(): an array of override Fields, some fields can be overriden, check FLDS<GO>, select a field and check bottom of the screen
' - OverrideValues(): the value to override the Fields
' - SetErrorMessagesToEmpty(): If True, will convert non-request breaking errors (eg: a field that does not apply to a Ticker such as Duration for an Equity)
' to an empty entry in the returned data table, if set to False (Default) will return the error code
' Output:
' - Will return an Array with 2 dimentions, in the 0 X you will find the Date column, in the 0 Y you will Find Field and Security Names
' - If there are multiple Tickers, in the description Header row the following formatting will occur: TickerName:FieldName
' - Note that the Dates for the returned values will be aligned, a missing date (eg: holiday) for one ticker but not another would be replaced by an empty value
Dim i As Long, j As Long
'1. Take the Mandatory Data
Dim ServiceType As String
bRequestType = CONST_REQUEST_TYPE_HISTORICAL ' By Definition
ServiceType = CONST_SERVICE_TYPE_REF ' By Definition
' 1.1 Verify Ticker Input
Dim NumTickers As Long, NumValidTickers As Long
Tickers = FlattenArray(Tickers)
NumTickers = LBound(Tickers, 1) + UBound(Tickers, 1) - 1
For i = 1 To NumTickers
If Tickers(LBound(Tickers, 1) + i - 1) <> "" Then
' A Ticker is Valid if non-empty
' Sending empty string Tickers will crash the application
NumValidTickers = NumValidTickers + 1
If NumValidTickers = 1 Then
ReDim bSecurities(1 To NumValidTickers)
Else
ReDim Preserve bSecurities(1 To NumValidTickers)
End If
bSecurities(NumValidTickers) = Tickers(LBound(Tickers, 1) + i - 1)
End If
Next i
If NumValidTickers = 0 Then
Err.Raise vbObjectError, "C_BBG.HistoricalData", "There are 0 non-empty Tickers provided!"
Exit Function
Else
bNumSecurities = NumValidTickers
End If
' 1.2 Verify Fields Input
Dim NumFields As Long, NumValidFields As Long, FlatFields() As Variant
Fields = FlattenArray(Fields)
NumFields = LBound(Fields, 1) + UBound(Fields, 1) - 1
For i = 1 To NumFields
If Fields(LBound(Fields, 1) + i - 1) <> "" Then
' A Field is Valid if non-empty string
' Sending an empty string field will crash the application
NumValidFields = NumValidFields + 1
If NumValidFields = 1 Then
ReDim bFields(1 To NumValidFields)
Else
ReDim Preserve bFields(1 To NumValidFields)
End If
bFields(NumValidFields) = Fields(LBound(Fields, 1) + i - 1)
End If
Next i
If NumValidFields = 0 Then
Err.Raise vbObjectError, "C_BBG.HistoricalData", "There are 0 non-empty Fields provided!"
Exit Function
Else
bNumFields = NumValidFields
End If
' 1.3 Verify StartDate and EndDate inputs
If CDbl(startDate) = 0 Then
Err.Raise vbObjectError, "C_BBG.HistoricalData", "Invalid Start Date Format: " & startDate
Exit Function
Else
bStartDate = ConvertDateToBloomberg(startDate)
End If
If CDbl(endDate) = 0 Then
Err.Raise vbObjectError, "C_BBG.HistoricalData", "Invalid End Date Format: " & endDate
Exit Function
Else
bEndDate = ConvertDateToBloomberg(endDate)
End If
If startDate > endDate Then
Err.Raise vbObjectError, "C_BBG.HistoricalData", "The Start Date: " & startDate & " is AFTER the End Date: " & endDate
Exit Function
End If
'2. Take and Verify the Optional Data
' 2.1 The General Overrides
Dim NumOvFields As Integer, NumOvValues As Integer, NumValidOvFieldsValues As Integer
If IsMissing(OverrideFields) = False Then
OverrideFields = FlattenArray(OverrideFields)
If IsMissing(OverrideValues) = True Then
Err.Raise vbObjectError, "C_BBG.HistoricalData", "You have provided overrideFields, but not overrideValues!"
Exit Function
Else
' Both overrideFields and overrideValues are provided, check they are the same size and have all non-empty inputs
OverrideValues = FlattenArray(OverrideValues)
NumOvFields = LBound(bOverrideFields, 1) + UBound(bOverrideFields, 1) - 1
NumOvValues = LBound(bOverrideValues, 1) + UBound(bOverrideValues, 1) - 1
ReDim bOverrideFields(1 To NumOvFields), bOverrideValues(1 To NumOvValues)
For i = 1 To NumOvFields
' Note that we check for pairs of non-empty Field, Value, if either is empty both are skipped
If OverrideFields(LBound(OverrideFields, 1) + i - 1) <> "" And OverrideValues(LBound(OverrideValues, 1) + i - 1) Then
NumValidOvFieldsValues = NumValidOvFieldsValues + 1
bOverrideFields(NumValidOvFieldsValues) = OverrideFields(LBound(OverrideFields, 1) + i - 1)
bOverrideValues(NumValidOvFieldsValues) = OverrideValues(LBound(OverrideValues, 1) + i - 1)
End If
Next i
End If
ElseIf IsMissing(OverrideValues) = False Then
Err.Raise vbObjectError, "C_BBG.HistoricalData", "You have provided overrideValues, but not overrideFields!"
Exit Function
End If
' 2.2 The Specific Historical Data Overrides
If Not VBA.IsMissing(calendarCodeOverride) = True Then bcalendarCodeOverride = calendarCodeOverride 'CDR <GO>
If Not VBA.IsMissing(calendarOverridesOperation) = True Then bcalendarOverridesOperation = calendarOverridesOperation ' CDR_AND;CDR_OR
If Not VBA.IsMissing(currencyCode) = True Then bcurrencyCode = currencyCode 'CCY ISO-3
If Not VBA.IsMissing(nonTradingDayFillOption) = True Then bnonTradingDayFillOption = nonTradingDayFillOption 'NON_TRADING_WEEKDAYS;ALL_CALENDAR_DAYS;ACTIVE_DAYS_ONLY
If Not VBA.IsMissing(nonTradingDayFillMethod) = True Then bnonTradingDayFillMethod = nonTradingDayFillMethod 'PREVIOUS_VALUE;NIL_VALUE
If Not VBA.IsMissing(periodicityAdjustment) = True Then bperiodicityAdjustment = periodicityAdjustment 'ACTUAL;CALENDAR;FISCAL
If Not VBA.IsMissing(periodicitySelection) = True Then bperiodicitySelection = periodicitySelection 'DAILY;WEEKLY;MONTHLY;QUARTERLY;SEMI_ANNUALLY;YEARLY
If Not VBA.IsMissing(maxDataPoints) = True Then bmaxDataPoints = maxDataPoints '
If Not VBA.IsMissing(pricingOption) = True Then bpricingOption = pricingOption 'PRINCING_OPTION_PRICE;PRICING_OPTION_YIELD
' 2.3 Set the ErrorMessage Policy
bSetErrorMessageToEmpty = SetErrorMessagesToEmpty
'3. Generate the Full Output Array/Matrix
' It will be reduced in size later
Dim NumDays As Long, Count As Integer
NumDays = DateDiff("d", startDate, endDate) + 1
If bNumSecurities > 1 Then
' We are going to join Ticker:Field
ReDim bOutputArray(0 To NumDays, 0 To bNumFields * bNumSecurities)
bOutputArray(0, 0) = "Date"
For i = 1 To bNumSecurities
For j = 1 To bNumFields
Count = Count + 1
bOutputArray(0, Count) = Aggregate_Ticker_Field(bSecurities(i), bFields(j))
Next j
Next i
Else
' We have only one Ticker, we output just Fields
ReDim bOutputArray(0 To NumDays, 0 To bNumFields)
For i = 1 To bNumFields
bOutputArray(0, i) = bFields(i)
Next i
End If
bOutputArray(0, 0) = "Date"
If OrderDescending = False Then
For i = 1 To NumDays
bOutputArray(i, 0) = startDate + i - 1
Next i
Else
For i = 1 To NumDays
bOutputArray(i, 0) = endDate - i + 1
Next i
End If
' 4. Open the Service
Dim HaveService As Boolean
HaveService = OpenService(ServiceType)
If HaveService = False Then
' Terminate early, return Empty, the error message has already been raised
Exit Function
End If
'5. Generate Request
Dim override As blpapicomLib2.Element
Set bRequest = bService.CreateRequest(bRequestType)
For i = 1 To NumValidTickers
bRequest.GetElement("securities").AppendValue bSecurities(i)
Next i
For i = 1 To NumValidFields
bRequest.GetElement("fields").AppendValue bFields(i)
Next i
bRequest.Set "startDate", bStartDate
bRequest.Set "endDate", bEndDate
If NumValidOvFieldsValues > 0 Then
Set bOverrides = bRequest.GetElement("overrides")
For i = 1 To NumValidOvFieldsValues
Set override = bOverrides.AppendElment()
override.SetElement "fieldId", bOverrideFields(i)
override.SetElement "value", bOverrideValues(i)
Next i
End If
If bcalendarCodeOverride <> "" Then bRequest.Set "calendarCodeOverride", bcalendarCodeOverride
If bcalendarOverridesOperation <> "" Then bRequest.Set "calendarOverridesOperation", bcalendarOverridesOperation
If bcalendarCodeOverride <> "" Then bRequest.Set "calendarCodeOverride", bcalendarCodeOverride
If bcurrencyCode <> "" Then bRequest.Set "currencyCoden", bcurrencyCode
If bnonTradingDayFillOption <> "" Then bRequest.Set "nonTradingDayFillOption", bnonTradingDayFillOption
If bnonTradingDayFillMethod <> "" Then bRequest.Set "nonTradingDayFillMethod", bnonTradingDayFillMethod
If bperiodicityAdjustment <> "" Then bRequest.Set "periodicityAdjustment", bperiodicityAdjustment
If bperiodicitySelection <> "" Then bRequest.Set "periodicitySelection", bperiodicitySelection
If bmaxDataPoints <> 0 Then bRequest.Set "maxDataPoints", bmaxDataPoints
If bpricingOption <> "" Then bRequest.Set "pricingOption", bpricingOption
' 6. Send the Request
Dim RequestId As blpapicomLib2.CorrelationId
On Error Resume Next
Set RequestId = bSession.SendRequest(bRequest)
If Err.Number <> 0 Then
Err.Raise vbObjectError, "C_BBG.HistoricalData", "Error: Could not send the Request, check that you have provided correct inputs!"
Exit Function
End If
On Error GoTo 0
' 7. Process the Incoming BBG Events
Call catchServerEvent
' 8. Redefine the Shape of the bOutputArray such that there are no empty rows (at least one data point per row)
Dim OutData() As Variant, PosDates() As Long, NumDates As Long, NumCols As Integer, HasValues As Boolean
' 8.1 Determine what are the Valid Dates
NumCols = UBound(bOutputArray, 2)
NumDates = -1 ' Initialised at -1 so that it can be defined from 0 to X
For i = 0 To UBound(bOutputArray, 1)
HasValues = False
For j = 1 To NumCols ' We avoid the Date in position j=0
If IsEmpty(bOutputArray(i, j)) = False And IsNull(bOutputArray(i, j)) = False Then
If VarType(bOutputArray(i, j)) = vbString Then
If Len(Trim(bOutputArray(i, j))) <> 0 Then
NumDates = NumDates + 1
If NumDates = 0 Then
ReDim PosDates(0 To NumDates)
Else
ReDim Preserve PosDates(0 To NumDates)
End If
PosDates(NumDates) = i
Exit For ' We have one value for this date, move to the next date
End If
Else
NumDates = NumDates + 1
If NumDates = 0 Then
ReDim PosDates(0 To NumDates)
Else
ReDim Preserve PosDates(0 To NumDates)
End If
PosDates(NumDates) = i
Exit For ' We have one value for this date, move to the next date
End If
End If
Next j
Next i
' 8.2 Recreate the bOutputArray excluding the empty dates
ReDim OutData(0 To NumDates, 0 To NumCols)
For i = 0 To NumDates
For j = 0 To NumCols
OutData(i, j) = bOutputArray(PosDates(i), j)
Next j
Next i
'9. Return the Data and Cleanup
HistoricalData = OutData
Call Terminate
End Function
Public Function AIMPortfolioPositionData(ByVal AccountType As String, _
ByVal AccountName As String, _
ByVal Fields As Variant, _
ByVal PX As Integer, _
Optional ByVal includeCash As Variant = False, _
Optional ByVal SetErrorMessageToEmpty As Boolean = False) As Variant
'Gets TSADF or MAV Position Data
' !!! UNTESTED !!!
' Inputs:
' - accountType: the Account or Fund Type: can be Account or Group, find it under AIM or MAV in the Terminal
' - accountName: the Name of the Portfolio or group of portfolios you want to get the positions from
' - Fields: the fields that you want to request (Some Fields may be AIM specific, or the normal API fields)
' - PX: The Pricing Number, can be obtained from your BBG rep, a 4 digits number
' - includeCash: if set to True will also return the cash positions of the Fund (may be innacurate depending on BBG and your Middle-Office)
' - SetErrorMessagesToEmpty(): If True, will convert non-request breaking errors (eg: a field that does not apply to a Ticker such as Duration for an Equity)
' to an empty entry in the returned data table, if set to False (Default) will return the error code
' Output:
' - A 2D Array, with Fields Names in the 0th Row, there is no 0th Column
Dim i As Integer
' 1. Take the Mandatory Data
Dim ServiceType As String
bRequestType = CONST_REQUEST_TYPE_PORTFOLIO
ServiceType = CONST_SERVICE_TYPE_PRT
' 1.1 Get the Type and Name
bentityType = AccountType
bentityName = AccountName
' 1.2 Get and Verify the Fields
Dim NumFields As Long, NumValidFields As Long, FlatFields() As Variant
Fields = FlattenArray(Fields)
NumFields = LBound(Fields, 1) + UBound(Fields, 1) - 1
ReDim bFields(1 To NumFields)
For i = 1 To NumFields
If Fields(LBound(Fields, 1) + i - 1) <> "" Then
' A Field is Valid if non-empty string
' Sending an empty string field will crash the application
NumValidFields = NumValidFields + 1
bFields(NumValidFields) = Fields(LBound(Fields, 1) + i - 1)
End If
Next i
If NumValidFields = 0 Then
Err.Raise vbObjectError, "C_BBG.AIMPortfolioPositionData", "There are no non-empty Fields provided!"
Exit Function
End If
' 1.3 Get the PX Information
bPx = PX
' 2. Take the Optional Data
bincludeCash = includeCash
' 2.1 Set the ErrorMessage Policy
bSetErrorMessageToEmpty = SetErrorMessageToEmpty
' 3. Generate the Output Array
Dim TempArray() As String
ReDim bOutputArray(0 To 1), TempArray(1 To UBound(bFields, 1) + 2) ' +2 as there are two default columns Position Ticker and Name
TempArray(1) = "TICKER"
TempArray(2) = "NAME"
For i = 1 To UBound(bFields, 1)
TempArray(i + 2) = bFields(i)
Next i
bOutputArray(0) = TempArray
' 4. Open the Service
Dim HaveService As Boolean
HaveService = OpenService(ServiceType)
If HaveService = False Then
' Terminate early, return Empty, the error message has already been raised
Exit Function
End If
' 5. Generate the Request
Set bRequest = bService.CreateRequest(bRequestType)
bRequest.GetElement("pxNum").SetValue PX
bRequest.GetElement("entityType").SetValue bentityType
bRequest.GetElement("entityName").SetValue bentityName
For i = 1 To UBound(bFields, 1)
bRequest.GetElement("fields").AppendValue bFields(i)
Next i
Dim parameterArray As blpapicomLib2.Element