How do I get trading holidays from the Bloomberg API - java

I'm using Bloomberg Java api to download trading data. I need somebody to tell me if there exists a function which can return a list of trading holidays. I looked through the manual but couldn't find one. If there's no such a thing, is there a good way that I can create one? Thanks.

String field = "CALENDAR_HOLIDAYS";
//String field = "CALENDAR_NON_SETTLEMENT_DATES";
Request request = this._refDataServiceM.CreateRequest("ReferenceDataRequest");
Element securities = request.GetElement("securities");
securities.AppendValue("AAPL US Equity");
Element fields = request.GetElement("fields");
fields.AppendValue(field);
Element overridefields = request.GetElement("overrides");
Element overrides = request.GetElement("overrides");
Element override1 = overrides.AppendElement();
override1.SetElement("fieldId", "SETTLEMENT_CALENDAR_CODE");
override1.SetElement("value", calendar_code);
Element override2 = overrides.AppendElement();
override2.SetElement("fieldId", "CALENDAR_START_DATE");
override2.SetElement("value", startDate.ToString("yyyyMMdd"));
Element override3 = overrides.AppendElement();
override3.SetElement("fieldId", "CALENDAR_END_DATE");
override3.SetElement("value", endDate.ToString("yyyyMMdd"));

The Bloomberg API will tell you, for a given security, the appropriate calendar code using DS853 (CALENDAR_CODE). Given a calendar code, I do not believe that Bloomberg provides a way to download a holiday calendar. You may need to use a third party vendor such as Financial Calendar.

I had issues getting the accepted answer to work. Turned out the SETTLEMENT_CALENDAR_CODE isn't needed. The following worked:
{
securities[] = {
/bbgid/BBG00HZZLBT7
}
fields[] = {
CALENDAR_NON_SETTLEMENT_DATES
}
overrides[] = {
overrides = {
fieldId = "CALENDAR_START_DATE"
value = "20180101"
}
overrides = {
fieldId = "CALENDAR_END_DATE"
value = "20190101"
}
}
tableOverrides[] = {
}
}
Response:
{
securityData[] = {
securityData = {
security = "UXA INDEX"
eidData[] = {
}
fieldExceptions[] = {
}
sequenceNumber = 0
fieldData = {
CALENDAR_NON_SETTLEMENT_DATES[] = {
CALENDAR_NON_SETTLEMENT_DATES = {
Holiday Date = ...
}
CALENDAR_NON_SETTLEMENT_DATES = {
Holiday Date = ...
}
...
}
}
}
}
}

The Bloomberg holiday data is lacking sometimes. You could try a service that specializes in trading holidays data like TradingHours.com.
https://www.tradinghours.com/docs/3.x/enterprise/market-holidays.html

The Python implementation is as follows. Note that we are using calendar "AM" for Amsterdam, marking the second day of easter as a national holiday.
refDataService = session.getService("//blp/refdata")
request = refDataService.createRequest("ReferenceDataRequest")
request.append("securities", "AAPL US Equity")
request.append("fields", "CALENDAR_HOLIDAYS")
overrides = request.getElement("overrides")
override2 = overrides.appendElement()
override2.setElement("fieldId", "CALENDAR_START_DATE")
override2.setElement("value", "20200101")
override3 = overrides.appendElement()
override3.setElement("fieldId", "CALENDAR_END_DATE")
override3.setElement("value", "20210501")
override4 = overrides.appendElement()
override4.setElement("fieldId", "SETTLEMENT_CALENDAR_CODE")
override4.setElement("value", "AM")
session.sendRequest(request)

Related

Stripe integration in Kotlin App -- IllegalStateException

I am integrating Stripe for Java in a Kotlin app.
This is the code that I wrote to create a Charge
createCharge function:
fun createCharge(charge: Charge, testApiKey: String): Charge? {
//met
// On your server, grab the Stripe token in the POST parameters submitted by your form. From there, it’s one simple API call to charge the card
Stripe.apiKey = testApiKey
try {
val chargeParams = mutableMapOf<String, Any?>()
chargeParams["amount"] = charge.amount
chargeParams["currency"] = charge.currency
chargeParams["description"] = charge.description
chargeParams["source"] = charge.source
chargeParams["customer"] = charge.customer
chargeParams["receipt_email"] = charge.receiptEmail
val requestOptions = idempotencyKeySetter()
val initialMetadata = mutableMapOf<String, String?>()
initialMetadata["start_date"] = charge.metadata["start_date"]
initialMetadata["end_date"] = charge.metadata["end_date"]
chargeParams["metadata"] = initialMetadata
return Charge.create(chargeParams, requestOptions)
} catch (e: StripeException) {
e.printStackTrace()
return null
}
}
and the function calling the createCharge function:
var formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
fun checkCreateCharge() {
val chargeParams: Charge = Charge()
chargeParams.amount = 2000
chargeParams.currency = "usd"
chargeParams.description = description
chargeParams.source = PaymentSource { "" }
chargeParams.customer = customerId
chargeParams.receiptEmail = testEmail
chargeParams.metadata["start_date"] = LocalDate.parse("2018-12-31", formatter).toString()
chargeParams.metadata["end_date"] = LocalDate.parse("2019-03-31", formatter).toString()
val newCharge: Charge? = createCharge(chargeParams, testApiKey)
}
When I the function checkCreateCharge runs, it sends the following error:
java.lang.IllegalStateException: chargeParams.metadata must not be null
Does anyone know why this is the case?
So while this is "possible" you absolutely should not do this. It's a very large security vulnerability. Anyone with your App would be able to sniff your Stripe Secret API Key and do any number of bad things. They could, for instance, test credit cards or even take money from your account.
When implementing Stripe on Android you should only use your Publishable API Key and only use the key to create Tokens/Sources. All other operations should leverage your Secret API Key on a secured backend.
Best I can tell from the API documentation, you're accessing getMetadata() which is returning null (as you've never set a value on it). Basically, the line:
chargeParams.metadata["start_date"] = LocalDate.parse("2018-12-31", formatter).toString()
is equivalent to the Java code:
chargeParams.getMetadata().put("start_date", LocalDate.parse("2018-12-31", formatter).toString())
and in your situation getMetadata() is null. I believe changing this to be:
chargeParams.setMetadata(
mapOf(
"start_date" to LocalDate.parse("2018-12-31", formatter).toString(),
"end_date" to LocalDate.parse("2019-03-31", formatter).toString()
)
)
will resolve the issue.

How to restrict user to verify the mobile by OTP after 4 hours of OTPgeneration

I have created Api for Verify mobile and i want to put some logic so
that i can restrict the user who try to verify otp after 4 hours. I
have created two Apis first one send otp to user and the input
parameter is mobile number.
Second API verify that mobile number by comparing the otp inserted by user and that stored in database during first API
#RestController
#RequestMapping("/api/v1")
public class MobileController2 {
private String To = null;
OtpGenerator otp = new OtpGenerator();
#Autowired
private MobileRepository mobileRepository;
Sms sms = new Sms();
Date date = new Date();
Timestamp timestamp1 = new Timestamp(date.getTime());
Calendar cal = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
#PostMapping(value = "/mobile", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Mobile> createMobile(#RequestBody Mobile mobile) {
int hashcode = otp.RandomOtp();
this.To = mobile.getMob();
String Message = hashcode + " is your Pharmerz verification code ";
if (mobileRepository.findByUserid(mobile.getUserid()) != null) {
Mobile mobileprevious = mobileRepository.findByUserid(mobile.getUserid());
mobileprevious.setMob(mobile.getMob());
mobileprevious.setHASHCODE("" + hashcode);
mobileprevious.setUpdated(mobile.getUpdated());
mobileprevious.setVERIFIED(0);
mobileRepository.save(mobileprevious);
sms.sms_generation(To, Message);
return new ResponseEntity<Mobile>(mobileprevious, HttpStatus.OK);
} else {
mobile.setHASHCODE("" + hashcode);
mobile.setVERIFIED(0);
mobileRepository.save(mobile);
sms.sms_generation(To, Message);
return new ResponseEntity<Mobile>(mobile, HttpStatus.OK);
}
}
#PostMapping(value = "/verifymobile", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Mobile> verifyMobile(#RequestBody Mobile mobile) {
String userid = mobile.getUserid();
String userotp = mobile.getHASHCODE();
Mobile mobileobject = mobileRepository.findByUserid(userid);
if (mobileobject.getHASHCODE().equals(userotp)) {
System.out.println("Matched");
mobileobject.setHASHCODE("");
mobileobject.setVERIFIED(1);
mobileRepository.save(mobileobject);
String Acknowledge = "Thank you for verifying on Pharmerz";
sms.sms_generation(To, Acknowledge);
return new ResponseEntity<Mobile>(mobileobject, HttpStatus.OK);
} else {
System.out.println("Miss matched");
return new ResponseEntity<Mobile>(HttpStatus.BAD_REQUEST);
}
}
}
Giving you a non-answer here: learn how to write helpful log messages and how to make use of tools such as debuggers or profilers.
Meaning: nobody can debug such a problem from remote. There could be all kinds of root causes giving you this behavior.
You have to step back and
understand that putting the string "error log" into your error log doesn't help anything.
understand that printing to the console ... is also not a reliable way to attain "logs" of your code. Especially when having the same message "Wrong or Old Otp" in three different places. That's called code duplication and per se a bad practice!
learn to use tools that give you insights about the health of your application.
In other words: the primary goal of logging information within your application is to enable you to debug problems after they took place. Exactly to support you in situations such as this.

NetSuite SOAP API (SuiteTalk) to dump General Ledger

Can anyone give me advice on how to read the general ledger using SuiteTalk, the SOAP API from NetSuite?
For example, if you look at an account or a transaction on the NetSuite UI, there is an option to select "GL Impact". This produces a list of relevant general ledger entries.
However, I couldn't figure out a way to get the same list using SuiteTalk. One initially promising SOAP operation I tried calling was getPostingTransactionSummary(), but that is just a summary and lacks detail such as transaction dates. Another way is to call search() passing a TransactionSearchBasic object. That returns too many types of transaction and I'm not sure which of those actually have an impact on the general ledger.
I'm using Java and Axis toolkit for the SOAP operations, but examples in any language whatsoever (or raw SOAP XML) would be appreciated.
you are on the right track with your transaction search.
You are looking for posting is true and where the line has an account.
However I'd set this up in the saved search editor at least until you've figured out how you are going to filter to manageable numbers of lines. Then use TransactionSearchAdvanced with savedSearchId to pull that info via SuiteTalk
I am able to search GL transaction with below code, this could help you.
public void GetTransactionData()
{
DataTable dtData = new DataTable();
string errorMsg = "";
LoginToService(ref errorMsg);
TransactionSearch objTransSearch = new TransactionSearch();
TransactionSearchBasic objTransSearchBasic = new TransactionSearchBasic();
SearchEnumMultiSelectField semsf = new SearchEnumMultiSelectField();
semsf.#operator = SearchEnumMultiSelectFieldOperator.anyOf;
semsf.operatorSpecified = true;
semsf.searchValue = new string[] { "Journal" };
objTransSearchBasic.type = semsf;
objTransSearchBasic.postingPeriod = new RecordRef() { internalId = "43" };
objTransSearch.basic = objTransSearchBasic;
//Set Search Preferences
SearchPreferences _searchPreferences = new SearchPreferences();
Preferences _prefs = new Preferences();
_serviceInstance.preferences = _prefs;
_serviceInstance.searchPreferences = _searchPreferences;
_searchPreferences.pageSize = 1000;
_searchPreferences.pageSizeSpecified = true;
_searchPreferences.bodyFieldsOnly = false;
//Set Search Preferences
try
{
SearchResult result = _serviceInstance.search(objTransSearch);
List<JournalEntry> lstJEntry = new List<JournalEntry>();
List<JournalEntryLine> lstLineItems = new List<JournalEntryLine>();
if (result.status.isSuccess)
{
for (int i = 0; i <= result.recordList.Length - 1; i += 1)
{
JournalEntry JEntry = (JournalEntry)result.recordList[i];
lstJEntry.Add((JournalEntry)result.recordList[i]);
if (JEntry.lineList != null)
{
foreach (JournalEntryLine line in JEntry.lineList.line)
{
lstLineItems.Add(line);
}
}
}
}
try
{
_serviceInstance.logout();
}
catch (Exception ex)
{
}
}
catch (Exception ex)
{
throw ex;
}
}

How to get last published date from a CmsResource in OpenCms

I'm unable to get the last published date of a resource. There is no way to do that with OpenCms API.
http://files.opencms.org/javadoc/core/org/opencms/file/CmsResource.html
That's very weird, it has to be stored in some place because OpenCms Workplace shows this information in the History option.
The method getDateReleased() from CmsResource class always returns DATE_RELEASED_DEFAULT until you set the availability of the resource.
Any thoughts?
Thanks!
Finally I achieve this by digging in the source code from OpenCms.
I found the solution here, in the getListItems method:
https://github.com/alkacon/opencms-core/blob/branch_8_5_x/src/org/opencms/workplace/commons/CmsHistoryList.java
So I built this method to get the last published date from any resource:
public static Date getLastPublishedDate(CmsJspActionElement cms, CmsResource resource) throws Exception {
CmsObject cmso = cms.getCmsObject();
String sitePath = cmso.getSitePath(resource);
if (cmso.readAllAvailableVersions(sitePath).size() > 0) {
I_CmsHistoryResource histRes = cmso.readAllAvailableVersions(sitePath).get(0);
int publishTag = histRes.getPublishTag();
CmsHistoryProject project = cmso.readHistoryProject(publishTag);
return new Date(project.getPublishingDate());
} else {
return null;
}
}
If NULL is returned then the resource has not been published yet.

How do I get all the calendar entries for a particular time range using Google Calendar API

I want to view events over specific time range for a specific calendar, but am having trouble using the API, It is a generic API, and it reminds me of using the DOM. The problem is that it seems difficult to work with because much of the information is in generic base classes.
How do I get the events for a calendar using Groovy or Java?
Does anybody have an example of passing credentials using curl?
Example code would be appreciated.
This document has examples for most of the common use cases. For example, here's the code for retrieving events for a specific time range
URL feedUrl = new URL("http://www.google.com/calendar/feeds/default/private/full");
CalendarQuery myQuery = new CalendarQuery(feedUrl);
myQuery.setMinimumStartTime(DateTime.parseDateTime("2006-03-16T00:00:00"));
myQuery.setMaximumStartTime(DateTime.parseDateTime("2006-03-24T23:59:59"));
CalendarService myService = new CalendarService("exampleCo-exampleApp-1");
myService.setUserCredentials("jo#gmail.com", "mypassword");
// Send the request and receive the response:
CalendarEventFeed resultFeed = myService.query(myQuery, Feed.class);
You could make this a bit Groovier, using something like:
def myQuery = new CalendarQuery("http://www.google.com/calendar/feeds/default/private/full".toURL()).with {
minimumStartTime = DateTime.parseDateTime("2006-03-16T00:00:00");
maximumStartTime = DateTime.parseDateTime("2006-03-24T23:59:59");
it
}
def myService = new CalendarService("exampleCo-exampleApp-1");
myService.setUserCredentials("jo#gmail.com", "mypassword");
// Send the request and receive the response:
def resultFeed = myService.query(myQuery, Feed);
If you do not need to alter the calendar, you only need to get the calendars private feed url, and you can use something like this (taken from the http://eu.gr8conf.org/agenda page). It uses the ICal4J library.
def url = "http://www.google.com/calendar/ical/_SOME_URL_/basic.ics".toURL()
def cal = Calendars.load(url)
def result = cal.components.sort { it.startDate.date }.collect {
def e = new Expando()
e.startDate = it.startDate.date
e.endDate = it.endDate.date
e.title = it.summary.value
if (it.location) {
e.presentation = Presentation.findByName(it.location.value, [fetch:"join"])
}
e.toString = {
"$startDate: $title"
}
return e
}
result
Happy hacking.

Categories