Showing posts with label email. Show all posts
Showing posts with label email. Show all posts

Monday, 1 June 2020

Trading Platform in C# Part 1 - Connect to TWS API

Create a trading platform in C#

Write a Windows form program in C# using Visual Studio and connect to Interactive Brokers Application Program Interface. I prefer writing GUI apps and not console apps. Other things you will need to do is sign up for a trial version of the Interactive Brokers trading software, if you already have an account with Interactive Brokers then great 

 

 

You will need to install 3 different software applications

 

Links to the programs that you need to install
Visual Studio 
https://visualstudio.microsoft.com/downloads/

Interactive Brokers Traders Workstation trading platform 
https://www.interactivebrokers.com/en/index.php?f=15876


Interactive Brokers API 
https://www.interactivebrokers.com/en/index.php?f=5041

Once you have downloaded and installed the above software you are ready to get started



# Control Name Text or Value
1 Button
btnConnect Connect
2 Combobox cbSymbol
MSFT
3 Listbox
lbData


Place this on line 19 in the EWrapperImpl.cs file


public Form1 myform;

Place the highlighted text in the tickPrice method within the EWrapperImpl.cs file


public virtual void tickPrice(int tickerId, int field, double price, TickAttrib attribs) 
        {
            Console.WriteLine("Tick Price. Ticker Id:" +tickerId+ ", Field: "+field+", Price: "+price+", CanAutoExecute: "+attribs.CanAutoExecute + 
                ", PastLimit: " + attribs.PastLimit + ", PreOpen: " + attribs.PreOpen);

            string strData = "Tick Price. Ticker Id:" + tickerId + ", Field: " + field +
                      ", Price: " + price + ", CanAutoExecute: " + attribs.CanAutoExecute;

            
            // Add this tick price to the form by calling the AddListBoxItem delegate
            myform.AddListBoxItem(strData);



        }

This is how the Form1.cs file should look.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using IBApi;

namespace IB_TradingPlatform
{
    public partial class Form1 : Form
    {
        // This delegate enables asynchronous calls for setting
        // the text property on a ListBox control.
        delegate void SetTextCallback(string text);

        public void AddListBoxItem(string text)
        {
            // See if a new invocation is required form a different thread            
            if (this.lbData.InvokeRequired)            
            {
                SetTextCallback d = new SetTextCallback(AddListBoxItem);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                // Add the text string to the list box
                this.lbData.Items.Add(text);
            }
        }

        // Create the ibClient object to represent the connection
        IB_TradingPlatform.EWrapperImpl ibClient;

        public Form1()
        {
            InitializeComponent();

            // instantiate the ibClient
            ibClient = new IB_TradingPlatform.EWrapperImpl();
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            // Parameters to connect to TWS are:
            // host       - IP address or host name of the host running TWS
            // port       - listening port 7496 or 7497
            // clientId   - client application identifier can be any number
            ibClient.ClientSocket.eConnect("", 7497, 0);

            var reader = new EReader(ibClient.ClientSocket, ibClient.Signal);
            reader.Start();
            new Thread(() => {
                while (ibClient.ClientSocket.IsConnected())
                {
                    ibClient.Signal.waitForSignal();
                    reader.processMsgs();
                }
            })
            { IsBackground = true }.Start();
            // Wait until the connection is completed
            while (ibClient.NextOrderId <= 0) { }

            // Set up the form object in the EWrapper
            ibClient.myform = (Form1)Application.OpenForms[0];

            getData();
        }

        private void getData()
        {
            ibClient.ClientSocket.cancelMktData(1); // cancel market data

            // Create a new contract to specify the security we are searching for
            IBApi.Contract contract = new IBApi.Contract();
            // Create a new TagValueList object (for API version 9.71 and later) 
            List<IBApi.TagValue> mktDataOptions = new List<IBApi.TagValue>();

            // Set the underlying stock symbol fromthe cbSymbol combobox            
            contract.Symbol = cbSymbol.Text;
            // 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";

            // If using delayed market data subscription un-comment 
            // the line below to request delayed data
            ibClient.ClientSocket.reqMarketDataType(3);  // delayed data = 3 live = 1

            // Kick off the subscription for real-time data (add the mktDataOptions list for API v9.71)
            
            // For API v9.72 and higher, add one more parameter for regulatory snapshot
            ibClient.ClientSocket.reqMktData(1, contract, "", false, false, mktDataOptions);
        }  
    }
}

Wednesday, 22 November 2017

Create an awesome mailing program in Python



# Craig Hammond 2017 YouTube channel bingazingas
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
# smtp.mail.yahoo.com
import time
from tkinter import *
from tkinter import ttk
import math

class Application(Frame):
    """ Gui Application """
    
    def __init__(self, master):
        """ initialize the Frame """
        ttk.Frame.__init__(self, master)

        self.grid()
        self.create_widgets()

    def create_widgets(self):

        myfont = ('', 14, 'bold')
        # row 0
        #create first button
        self.btnConnect = Button(self,  font=myfont, text = "Send Mail", bg='red', fg='white', command=self.send_mail).grid(row=0, column=0, sticky=W)
        
        # row 1
        # create label for To:
        self.label1 = Label(self, font=myfont, text='To: ').grid(row=1, column=0, pady=10, padx=10, sticky=E)

        # create combo box for the address
        self.cbToEmail = ttk.Combobox(self, font=myfont, width=40, textvariable=varTo)
        self.cbToEmail['values'] = ('info@evil_corp.com', 'admin@yahoos.com', 'bobhatesthat@yahoo.com', 'juggernaut@gmail.com')
        self.cbToEmail.grid(row=1, column=1, pady=10, padx=10)
        
        # row 2
        # create label from
        self.label2 = Label(self, font=myfont, text='From: ').grid(row=2, column=0, pady=10, padx=10, sticky=E)

        # create combo box for the address
        self.cbFromEmail = ttk.Combobox(self, font=myfont, width=40, textvariable=varFrom)
        self.cbFromEmail['values'] = ('info@yahhoo.com',
                                      'juggernaut@gmail.com',
                                      'evil_corp@yahoo.com')
        self.cbFromEmail.grid(row=2, column=1, pady=10, padx=10)
        
        # row 3
        # create label list of email addresses
        self.label3 = Label(self, font=myfont, text='Subject: ').grid(row=3, column=0, pady=10, padx=10, sticky=E)
        
        # create combo box for the address
        self.cbSubject = ttk.Combobox(self, font=myfont, width=40, textvariable=varSubject)
        self.cbSubject['values'] = ('check out my latest update from my website', 'Webist has been updated')
        self.cbSubject.grid(row=3, column=1, pady=10, padx=10)
        
        # row 4
        # create label list of email addresses
        self.label2 = Label(self, font=myfont, text='Address list name: ').grid(row=4, column=0, pady=10, padx=10, sticky=E)

        # create combo box for the address
        self.cbEmail_List = ttk.Combobox(self, font=myfont, width=40, textvariable=varEmail_List)
        self.cbEmail_List['values'] = ('adresses_email.txt',
                                       'Test_adresses_email.txt')
        self.cbEmail_List.grid(row=4, column=1, pady=10, padx=10)
        
        # row 5
        # create text box to hold the text for the letter
        self.text = Text(self, font=('', 12), width=90, height=25)
        self.text.grid(row=5, column = 0, columnspan=2, padx=5, pady=5, sticky='nsew')
        
        self.scrollb = Scrollbar(self, command=self.text.yview)
        self.scrollb.grid(row=5, rowspan=8, column=2, columnspan=2, pady=10, sticky='nse')
        self.text['yscrollcommand'] = self.scrollb.set

    def send_mail(self):
        
        from_address = varFrom.get() # get the address from the combobox who is sending the email example: 'sender_name@yahoo.com' 
        to_address = varTo.get() # get the address from the combobox for example: 'receiver_name@gmail.com'

        file_to_open = varEmail_List.get()# get address text file from combobox on form
        address_text = open(file_to_open,'r') # read the file
        my_addresses = address_text.readlines() # read each line in text file
        address_text.close() # close text file

        
        text_Letter = self.text.get('1.0', END) # select all text in the listbox 


        counter = 1 # create a varialbe to increase an integer
        # loop through all the addresses and print them
        for line in my_addresses:
            print (counter, line)
            counter +=1
   
        subject_text = varSubject.get() # gets the contents of the combo box for the subject line

        username = 'username@yahoo.com'  # use your email address as the username
        password = 'password' # password used to login to your email account
 
        b=1 # create a counter set it to start at 1
        
        # how many email addresses to process
        list_length = len(my_addresses)
        t = list_length 
        print ('How many in the list', list_length)
        
        msg = MIMEMultipart()
        msg['From'] = from_address
        msg['To'] = to_address
        msg['Subject'] = subject_text 
        msg.attach(MIMEText(text_Letter))
        server = smtplib.SMTP('smtp.mail.yahoo.com') # for gmail use: smtp.gmail.com
        server.ehlo()
        server.starttls()
        server.ehlo()
        server.login(username, password)
        for atoaddress in my_addresses: # loop through each email address
            ti = t % 12 # divide number by 12 send 12 at a time
            if ti == 0: # if when you divide the number by 12 you get zero
                server.sendmail(from_address,atoaddress,msg.as_string())
                print (b, ' sent ', atoaddress) # print the address that you sent the mail to
                time.sleep(2)
                server.quit() # quit or close the server
                print ('it_quit')
                time.sleep(8) # sleeps for 8 seconds
                msg = MIMEMultipart() # re-connects and continues the main loop
                msg['From'] = from_address
                msg['To'] = to_address
                msg['Subject'] = subject_text
                msg.attach(MIMEText(text_Letter))
                server = smtplib.SMTP('smtp.mail.yahoo.com') # for gmail use: smtp.gmail.com
                server.ehlo()
                server.starttls()
                server.ehlo()
                server.login(username, password)
                b+=1
                t-=1
            else:
                server.sendmail(from_address,atoaddress,msg.as_string())
                print (b, ' sent ', atoaddress)
                b+=1
                t-=1
                time.sleep(6)
        server.quit()
        print ('Done')


root = Tk()
   
root.title("email program in Python please donate")
root.geometry("840x625")
"""root.bind("", keydown)
root.bind("", keyup)"""
root.attributes("-topmost", True)
varTo = StringVar(root, value='to_address@gmail.com')
varFrom = StringVar(root, value='from_address@yahoo.com')
varText_Letter = StringVar()
varSubject = StringVar(root, value='Latest update from my website')
varEmail_List = StringVar(root, value='adresses_email.txt')
app = Application(root)

root.mainloop()


Save Save Save