I'm using Visual Studio to design a software that uses IBKR API to buy stocks. It's working fine if I'm buying integer stocks but I'm not able to buy fractional stocks.
I have found the function order.CashQty but it's not working.. this is the code that I'm using to buy, and it's working when I'm trying to buy integer stocks. Do you have any suggestion?
public void send_order(string side)
{
IBApi.Contract contract = new IBApi.Contract();
contract.Symbol = Global_variable.stock_sel;
contract.SecType = "STK";
contract.Exchange = cbMarket.Text;
contract.PrimaryExch = "ISLAND";
contract.Currency = "USD";
IBApi.Order order = new IBApi.Order();
order.OrderId = order_id;
order.Action = side;
order.OrderType = cbOrderType.Text;
//order.CashQty = 33.5; <-- maybe is this the way to buy fractionale share?
order.TotalQuantity = 1;
if (cbOrderType.Text == "STP")
{
order.AuxPrice = Convert.ToDouble(numPrice.Value);
}
order.DisplaySize = Convert.ToInt32(tbVisible.Text);
order.OutsideRth = chkOutside.Checked;
ibClient.ClientSocket.placeOrder(order_id, contract, order);
order_id++;
tbValid_Id.Text = Convert.ToString(order_id);
}
Thank you very much!
that code of my program, I hope that will help you:
private void buyStock(string symbol)
{
// Create a new contract to specify the security we are searching for
IBApi.Contract contract = new IBApi.Contract();
// Set the underlying stock symbol from the cbSymbol combobox
contract.Symbol = symbol.ToUpper();
// Set the Security type to STK for a Stock
contract.SecType = "STK";
// Use "SMART" as the general exchange
contract.Exchange = "SMART";
// Set the primary exchange (sometimes called Listing exchange)
// Use either NYSE or ISLAND
contract.PrimaryExch = "ISLAND";
// Set the currency to USD
contract.Currency = "USD";
IBApi.Order order = new IBApi.Order();
// gets the next order id from the text box
order.OrderId = order_id;
// gets the side of the order (BUY, or SELL)
order.Action = "BUY";
// gets order type from combobox market or limit order(MKT, or LMT)
order.OrderType = "MKT";
// number of shares from Quantity
order.TotalQuantity = 400;
// Value from limit price
//order.LmtPrice = Convert.ToDouble(numPrice.Text);
//
//Visible shares to the market
// order.DisplaySize = Convert.ToInt32(tbVisible.Text);
//order.OutsideRth = cbOutsideRTH.Checked;
//order.OutsideRth = chkOutside.Checked;
// Place the order
ibClient.ClientSocket.placeOrder(order_id, contract, order);
// increase the order id value
order_id++;
}
Related
We have one product with 4 different prices(basic, middle etc). Let's say user bought basic package (payment session is created after payment completion subscription created),but after a while, user decided to change his package and upgrade to advanced package. In that case should i use update subscription ?
This actually updates from X$ to the Y$ package
var service = new SubscriptionService();
Subscription subscription = service.Get("sub_49ty4767H20z6a");
var items = new List<SubscriptionItemOptions> {
new SubscriptionItemOptions {
Id = subscription.Items.Data[0].Id,
Price = "price_CBb6IXqvTLXp3f",
},
};
var options = new SubscriptionUpdateOptions {
CancelAtPeriodEnd = false,
ProrationBehavior = "create_prorations",
Items = items,
};
subscription = service.Update("sub_49ty4767H20z6a", options);
or just cancel current subscription and create new one ? Why am i asking this, because i chatted with support guys from Stripe, and got two different answers. One of them told me that i need to use update_subscripton, the another one told that i need to attach new subscription. I am confused.
The way that you've described this here, the update to upgrade the subscription makes more sense to me. Pay careful attention to the intended proration behaviour (do you want to credit the time left on the current plan) and whether you want to shift the billing period.
I'd also point out that you should consider switching to separate Products. A Product is a single good/service that you sell, while Prices represent different billing intervals and currencies. If you imagine some service with Silver, Gold and Platinum access levels, each of those is a different product -- they get more features! The Product is what gets shown on the invoice, too. So unless you use separate Products, the invoices would be indistinguishable aside from the rate paid.
Most of the time doing what you've done doesn't present any specific obsdtacles, but the Customer Portal enforces one price per product per interval. If you had two annual prices for the "same product" but different amount, why would anybody pay the higher price? It's because they're paying for something different, a different product.
Quick Answer
Upgrade (From Basic to Pro)
Remove Basic
Add Pro
Prorate (Do not change billing cycle)
// subscriptionId -> your subscription id
// additionalStripePriceIds -> stripe price id you are going to add
// removalStripePriceIds -> stripe price id you are going to remove
var getService = new SubscriptionService();
var getServiceResult = await getService.GetAsync(subscriptionId);
var items = new List<SubscriptionItemOptions>();
if (removalStripePriceIds != null && removalStripePriceIds.Any())
{
foreach (var removalStripePriceId in removalStripePriceIds)
{
var item = getServiceResult.Items.Data.FirstOrDefault(i => i.Price.Id == removalStripePriceId);
if (item != null)
{
var subscriptionItemOption = new SubscriptionItemOptions
{
Id = item.Id,
Deleted = true,
};
items.Add(subscriptionItemOption);
}
}
}
foreach (var additionalStripePriceId in additionalStripePriceIds)
{
var subscriptionItemOption = new SubscriptionItemOptions
{
Price = additionalStripePriceId,
};
items.Add(subscriptionItemOption);
}
var updateService = new SubscriptionService();
var updateOptions = new SubscriptionUpdateOptions
{
CancelAtPeriodEnd = false,
ProrationBehavior = "create_prorations",
Items = items,
};
await updateService.UpdateAsync(subscriptionId, updateOptions);
My problem is that after creating an invoice, I can never get new line items to reference their corresponding sales order line item.
I have been generating invoices via SuiteTalk. When I initially create an invoice, I empty the lineItemList and add back in the items I need. I make sure the orderLine property matches the sales order line item line number. This works great.
But when I try and update the invoice with additional line items, I can never get the new items to retain their orderLine property. The orderLine property is used for the "Invoiced" column on the Sales Order.
In order to get the referencing to be correct, I need to delete the invoice and create it again with all of the line items I need.
Does anyone know if what I am trying to do is possible?
In this example, I use this CreateInvoice function to create the invoice from scratch and add it to NetSuite. Everything works as expected.
public void CreateInvoice(SalesOrder salesOrder) {
Invoice brandNewInvoice = new Invoice() {
createdFrom = new RecordRef() {
internalId = salesOrder.internalId,
},
entity = salesOrder.entity,
tranDate = endDate,
tranDateSpecified = true,
startDate = startDate,
startDateSpecified = true,
endDate = endDate,
endDateSpecified = true,
itemList = new InvoiceItemList(),
};
invoice.itemList.item = GetInvoiceItemList(salesOrder); //see the function shown further down
netSuiteService.add(brandNewInvoice);
}
In this example, the invoice is already created and so I get it from NetSuite and then replace the existing itemList with a new one. After the update, the invoice will now have NO orderLine property for any of the line items. The invoice also loses its "Created From" field because there are no line items with the orderLine property set.
public void UpdateInvoice(SalesOrder salesOrder, String invoiceInternalId) {
Invoice invoice = GetNetSuiteInvoice(invoiceInternalId);
invoice.itemList.item = GetInvoiceItemList(salesOrder); //see the function shown further down
netSuiteService.update(invoice);
}
this is the function used to create the itemList:
public InvoiceItem[] GetInvoiceItemList(SalesOrder salesOrder) {
InvoiceItem[] invoiceItemList = new InvoiceItem[salesOrder.itemList.item.Length];
for (int i = 0; i < salesOrder.itemList.item.Length; i++) {
SalesOrderItem soItem = salesOrder.itemList.item[i];
double quantity = 1;
invoiceItemList[i] = new InvoiceItem() {
item = new RecordRef() {
internalId = soItem.item.internalId,
name = soItem.item.name,
},
amount = quantity * Double.Parse(soItem.rate),
amountSpecified = true,
quantity = quantity,
quantitySpecified = true,
price = new RecordRef() {
internalId = soItem.price.internalId,
name = soItem.price.name,
},
rate = soItem.rate,
orderLine = soItem.line, //this will establish the link between the invoice and the sales order
orderLineSpecified = true,
taxRate1 = soItem.taxRate1,
taxRate1Specified = true,
};
}
return invoiceItemList;
}
Actually what you are looking for is the intialize operation. You need to use initialize in order for Netsuite to properly fill in the created from and orderline props. From the NS Help there is a C# example of creating a Cash Sale:
private void Initialize()
{
this.login(true);
InitializeRef ref1 = new InitializeRef();
ref1.type = InitializeRefType.salesOrder;
//internal id of the sales order to be converted to cash sale
ref1.internalId = "792";
ref1.typeSpecified = true;
InitializeRecord rec = new InitializeRecord();
rec.type = InitializeType.cashSale;
rec.reference = ref1;
ReadResponse read1 = _service.initialize(rec);
}
This is normal, when transforming a transaction to another transaction (e.g. SO to Inv, PO to IR). When you transform, most of the information from the source transaction will be carried over. Like what you are doing which is creating an Invoice from Sales Order(Base on your code below).
createdFrom = new RecordRef() {
internalId = salesOrder.internalId,
},
You don't need to get the line item information from the Sales Order and put it in the Invoice because it will be pre-populated once you create it form Sales Oder(unless you need to change a value of a line item column).
One behavior of a transformed record(Invoice in your case), if you remove a line item from the Invoice you will lose the link to the Sales order(orderLine) and if you remove all the line item you will totally lose the link between the two transactions (createdfrom). This is what you are experiencing. orderLine/createdFrom is a field populated by the system, it looks like you are populating it but you are not.
I have code to Create a Vendor Payment for aVendor Bill like this :
InitializeRecord ir = new InitializeRecord();
ir.type = InitializeType.vendorPayment;
InitializeRef iref = new InitializeRef();
iref.typeSpecified = true;
iref.type = InitializeRefType.vendorBill;
iref.internalId = vendorBillId;
ir.reference = iref;
Login();
ReadResponse getInitResp = _service.initialize(ir);
if (getInitResp.status.isSuccess)
{
Record rec = getInitResp.record;
((VendorPayment)rec).total = (double)amount; //I don't want to pall all, just pay a half or just an amount less than the total
((VendorPayment)rec).totalSpecified = true;
WriteResponse writeRes = _service.add(rec);
return writeRes.status;
}
That can create a payment but the total is not apply, the payment is pay all amount of vendor bill's total.
I don't know what I'm missing here.
While applying payments to bill you cannot change the body level amount field. you got to change the amount line level field on apply line item record. I am not sure on syntax in Suitetalk, but, that should work.
I am trying to directly charge the customer using Stripe. I am using this sample code:
var stripeChargeCreateOptions = new StripeChargeCreateOptions();
stripeChargeCreateOptions.Amount = 1000;
stripeChargeCreateOptions.Currency = "usd";
stripeChargeCreateOptions.Description = "Test";
stripeChargeCreateOptions.Source = new StripeSourceOptions()
{
Number = "4242424242424242",
ExpirationYear = "2022",
ExpirationMonth = "10",
AddressCountry = "US", // optional
AddressLine1 = "24 Beef Flank St", // optional
AddressLine2 = "Apt 24", // optional
AddressCity = "Biggie Smalls", // optional
AddressState = "NC", // optional
AddressZip = "27617", // optional
Name = "Joe Meatballs", // optional
Cvc = "1223" // optional
};
stripeChargeCreateOptions.Capture = true;
var stripeChargeService = new StripeChargeService();
StripeCharge stripeCharge = stripeChargeService.Create(stripeChargeCreateOptions);
This seems to work in test mode. Here are my 3 questions:
The amount 1000 here is 10 USD - right?
Will this also work using live keys? I heard Stripe does not allow direct charge and requires us to their Javascript and store token for us to actually charge? How is it working in test mode?
What is the importance of stripeChargeCreateOptions.Capture = true; What would happen if I set it to false?
Yes, that's right. All amounts are in cents/pence.
I don't know enough about Stripe to help you with this one I'm afraid.
This tells Stripe what process to use to carry out the transaction - it's the second half of a charge previously created with the Capture property set to 'false'. So you would later need to call the API with it set to true to actually complete the charge. See the API for more information: https://stripe.com/docs/api?lang=php#capture_charge
I'm having trouble with NHibernate, First let me say I'm not native English talker, OK, let get to point.
As i face this error, i searched over the internet, and saw lot of people talking about it, but most of them had issue with cascade attribute, and totally if i wanna say, non matched my case, or even if it did i couldn't get through.
My Database is so small, but a bit complex.
My model files generated using Entity Developer.
As you can see there is inheritance, one-to-many and many-to-many relation ships,
As I am new to NHibernate, i write a test code, my normal test worked, till i add this many-to-many relation ship.
So i write this code:
//Owner o = new Owner
//{
// //OwnerId = Guid.NewGuid(),
// CellPhone1 = null,
// CellPhone2 = "09132198895",
// Phone = "03114335502",
// Firstname = "Hassan",
// Lastname = "Faghihi",
// OwnerTitle = PersonTitle.Mr
//};
//OwnerFactory ownerFactory = new OwnerFactory();
//ownerFactory.SaveOwner(o);
//SellHouse sh = new SellHouse
//{
// //ItemId = Guid.NewGuid(),
// Owner = o,
// Address = "dsasd",
// BuildYear = 1393,
// City = "Isfahan",
// Code = "A-512",
// Country = "Iran",
// Description = "Nothing",
// Dimensions = "4X5",
// Directions = Directions.North | Directions.South,
// Document = "dasd",
// Exchange = true,
// Facilities = Facilities.Elevator | Facilities.KichenMdfService | Facilities.Parking | Facilities.Warehouse,
// Floor = 4,
// HasYard = false,
// HouseType = HouseType.Apartment,
// IssueDate = DateTime.Now,
// Loan = 3124,
// Meter = 130,
// NumberOfBlocks = 4,
// NumberOfFloors = 0,
// OtherFacilities = "Nothing",
// Rooms = 2,
// ShareOfSixPart = 4.2f,
// State = "Isfahan",
// District = "kaveh",
// ExchangeDescription = "",
// Images = null,
// IsRented = false,
// Maps = null,
// MortgagePayed = 0,
// Price = 2222222,
// RentAmount = 0,
// Substructure = 4,
//};
GalleryFactory galleryFactory = new GalleryFactory();
Gallery g = new Gallery
{
Image = Properties.Resources.jeans_texture03.ToByte()
};
galleryFactory.SaveGallery(g);
SellHouseFactory sellHouseFactory = new SellHouseFactory();
//factory.SaveSellHouse(sh);
HashSet<Gallery> galleries = new HashSet<Gallery>();
galleries.Add(g);
SellHouse sellHouse = sellHouseFactory.GetSellHouses().FirstOrDefault();
if (sellHouse != null)
{
comboBox1.SelectedIndex = (int)sellHouse.Owner.OwnerTitle;
textBox1.Text = sellHouse.Owner.Firstname+sellHouse.Owner.Lastname;
//sellHouse.Images = galleries;
sellHouseFactory.SaveSellHouse(sellHouse);
}
i create an object of Owner, then save it, and pass it to sellHouse, and set Images and Maps (which are my many-to-many relation) to null.
so the sellHouse Created.
then i was wonder how to add image or map to my sellHouse,
So i pass a list containing one gallery element to sellHouse Maps property.
And it generate "Illegal attempt to associate a collection with two open sessions", first i though the reason is because my Gallery didn't saved before i pass it to sell house, so i did as you can see on my code, and did it manually.
But it still keep on generating that error...
I provide required file so, you can set up an example and understand my code better.
I'm very eager to hear your answer,cause my hands are tied do to my little knowledge over Hibernate and NHibernate.
Sources in DropBox:
enter link description here
Probably in all of your factory method you open a new session.
But you have to open just one session in every thread (or transaction).