[
  {
    "objectID": "reference/Contract.html",
    "href": "reference/Contract.html",
    "title": "Contract",
    "section": "",
    "text": "Contract(self, contract_params=None)\nCreate a contract\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\ncontract_params\ndict\nFirst number to add.\nNone\n\n\n\n\n\n\n\n\n\nType\nDescription\n\n\n\n\nContract\nA Contract object",
    "crumbs": [
      "Reference",
      "ShinyBroker Objects",
      "Contract"
    ]
  },
  {
    "objectID": "reference/Contract.html#parameters",
    "href": "reference/Contract.html#parameters",
    "title": "Contract",
    "section": "",
    "text": "Name\nType\nDescription\nDefault\n\n\n\n\ncontract_params\ndict\nFirst number to add.\nNone",
    "crumbs": [
      "Reference",
      "ShinyBroker Objects",
      "Contract"
    ]
  },
  {
    "objectID": "reference/Contract.html#returns",
    "href": "reference/Contract.html#returns",
    "title": "Contract",
    "section": "",
    "text": "Type\nDescription\n\n\n\n\nContract\nA Contract object",
    "crumbs": [
      "Reference",
      "ShinyBroker Objects",
      "Contract"
    ]
  },
  {
    "objectID": "query_and_display_market_data.html",
    "href": "query_and_display_market_data.html",
    "title": "Query and Display Market Data",
    "section": "",
    "text": "So you’ve installed Shinybroker and gotten the hello world example to work. Congrats! Now it’s time to actually build an app that uses some of the features.\nThis example will introduce you, in steps, to using ShinyBroker to write an app that will calculate beta between two assets, display that information, and use it to trade. Each step below adds a layer of functionality to the app. You can use this example to learn how to:\n\naccess & use the ShinyBroker reactive variables in sb_rvs\nimplement some initial setup logic to fetch data from IBKR\nprocess your data and display it\n\nComing Soon: live updating data, dynamic contract entry, positions, order placement, and finally– a video walkthrough of all this :)\n\nStep 1: sb_rvs and setup logic\nWe’re interested in calculating beta between two assets, so first we’re going to need to pull price data from IBKR in order to make the calculation.\nWe can accomplish this task with the code below, which operates as follows:\n\nDefines a Shiny server function\nSets a reactive variable named run_once\nDefines a setup function named make_historical_data_queries that fetches data for Apple & the S&P 500 index. Don’t worry, in later steps we’ll add the ability to dynamically pick what two assets you want, but for now we’ll hard-code the logic for Apple and SPX.\nCreates an app object from the server function that connects to a running instance of TWS (don’t forget run TWS or else it can’t connect!)\nRuns the app.\n\n\nThe Design Pattern\nThe server function, appropriately named a_server_function, first sets the value of a reactive variable named run_once to True. That design pattern is needed because start_historical_data_subscription can only be called within a reactive context, and also because when the shiny app loads, the reactive variables in a_server_function will be registered, set, and detected by the setup function make_historical_data_queries only after ShinyBroker has connected to TWS. In other words, by the time run_once is set, detected by make_historical_data_queries, and triggers the data fetching logic, you can be sure that the socket connection to IBKR (which takes place in the ShinyBroker backend) is set up and ready for use.\n\n\nThe setup function\nOnce triggered, make_historical_data_queries makes two calls to start_historical_data_subscription, a function provided by the ShinyBroker library. Even though in this case we’re performing a static, one-time data query, the word “subscription” appears in the function’s name because it can be called by setting the keepUpToDate parameter to True. Doing so results in the historical data being kept up-to-date with live market data as it becomes available, and we’ll do exactly this in a later step.\nFor now, you should understand three things about start_historical_data_subscription:\n\nThe data it fetches is written to the reactive variable named ‘historical_data’. Because this is a native ShinyBroker reactive variable, you can always access it with sb_rvs['historical_data']\nsb_rvs['historical_data'] is a dictionary that contains the data retrieved by each query. That dictionary is keyed by the integer-valued subscription_id you pass to it. If you don’t pass a subscription id, as in the code below, then ShinyBroker will just find the maximum subscription id already used in a historical data query for that session, add 1 to that, and treat the result as the subscription_id, beginning with 1 if no previous subscriptions are found for the current session.\nYou must define the contract for which you want data using the Contract constructor, which is provided by the ShinyBroker package.\n\n\nRun the code below\n\nView your Shiny app in a browser\nNavigate to the Market Data panel\nOpen the “Historical Data” accordion panel …and you should see an output of the historical data fetched by your query! Once you’ve successfully accomplished that, you can move on to the next step!\n\n\nimport select\nimport shinybroker as sb\nfrom shiny import Inputs, Outputs, Session, reactive\n\n\n# Declare a server function...\n#   ...just like you would when making an ordinary Shiny app.\n# remember that your server functions must always include the five inputs that\n#   appear in the signature below.\ndef a_server_function(\n        input: Inputs, output: Outputs, session: Session, ib_socket, sb_rvs\n):\n    # Only set this variable once. Reactive functions that depend upon it will\n    #   run when the app is initialized, after the socket has been connected\n    #   and properly set up by ShinyBroker.\n    run_once = reactive.value(True)\n\n    @reactive.effect\n    @reactive.event(run_once)\n    def make_historical_data_queries():\n\n        # Fetch the hourly trade data for AAPL for the past 3 days.\n        sb.start_historical_data_subscription(\n            historical_data=sb_rvs['historical_data'],\n            hd_socket=ib_socket,\n            contract=sb.Contract({\n                'symbol': \"AAPL\",\n                'secType': \"STK\",\n                'exchange': \"SMART\",\n                'currency': \"USD\",\n            }),\n            durationStr=\"3 D\",\n            barSizeSetting=\"1 hour\"\n        )\n\n        # Do the same, but for the S&P 500 Index\n        sb.start_historical_data_subscription(\n            historical_data=sb_rvs['historical_data'],\n            hd_socket=ib_socket,\n            contract=sb.Contract({\n                'symbol': 'SPX',\n                'secType': 'IND',\n                'currency': 'USD',\n                'exchange': 'CBOE'\n            }),\n            durationStr=\"3 D\",\n            barSizeSetting=\"1 hour\"\n        )\n\n\n# create an app object using your server function\n# Adjust your connection parameters if not using the default TWS paper trader,\n#   or if you want a different client id, etc.\napp = sb.sb_app(\n    server_fn=a_server_function,\n    host='127.0.0.1',\n    port=7497,\n    client_id=10742,\n    verbose=True\n)\n\n# run the app.\napp.run()"
  },
  {
    "objectID": "index.html",
    "href": "index.html",
    "title": "Overview",
    "section": "",
    "text": "Welcome! The ShinyBroker package and this website are under frequent heavy development, with new features and examples posted almost daily as they are written and tested.\nShinyBroker is based on the realization that in trading, everything is a reactive variable. Your orders, the prices of assets you’re tracking, current positions, Greeks, p/l– everything is time-dynamic, and can trigger trade order events according to algorithms written by the user. In ShinyBroker, those dynamic variables are kept updated over a socket connection to your account – live or paper – at Interactive Brokers, and are made accessible within Posit’s Shiny framework – a brilliant piece of coding that provides a natural sandbox for reactive variables and their live visualization as webpages.\nThe ‘hello world’ example below will walk you through a trivial setup case. You do not need an account at Interactive Brokers in order to follow the example, but it is suggested that you set up a free paper trader account with them if you’re interested in keeping track of your trades."
  },
  {
    "objectID": "index.html#hello-world-example",
    "href": "index.html#hello-world-example",
    "title": "Overview",
    "section": "Hello World Example",
    "text": "Hello World Example\nRun the base ShinyBroker app, and inject a simple bit of UI & server code.\n\nDownload and install TWS Latest for your OS. TWS (Trader Workstation) is what ShinyBroker connects to in order to communicate with IBKR and the market exchanges. Whenever you use ShinyBroker, you’ll need to have TWS open and running.\nOpen up TWS and sign in to the demo by clicking the link indicated by the yellow rectangle below. You’ll be asked for an email and whether or not you’d like IBKR to contact you. If you have a paper account already then you can certainly use it, so just sign in as usual. \nOnce you’re signed in, familiarize yourself with the system until you’re ready to move on. If you used a demo account, know that any trades you make will be erased when you log out.\nOpen the API Configuration menu using the File dropdown. You can find the menu at File &gt; Global Configuration &gt; API &gt; Settings.\nCheck Enable ActiveX and Socket Clients\nUn-check Read-only API\nYou can leave the rest of the settings alone. By default, your settings menu should look like the below: \nInstall ShinyBroker with pip install shinybroker\nIn Python, run the following: (make sure TWS is open and running)\n\n\nimport shinybroker as sb\n\n# Create an instance of a ShinyBroker App object using the default ui and server\napp = sb.sb_app(\n    host='127.0.0.1',  # localhost TWS is being served on your local machine\n    port=7497,         # make this match the port in your API Settings config\n    client_id=10742    # picked at random, choose another Client ID if preferred\n)\n\n# Run the app\napp.run()\n\nThis code performs three main operations:\n\nDefines where ShinyBroker can find a running instance of an IBKR client (TWS) (host and port) and what client ID to use when connecting (client_id)\nCreates a ShinyBroker sb_app object\nRuns the app\n\n\nClick the link in the command line to open up a web browser at localhost and explore the app.\n\nNote that there is nothing in the “home” tab. That space is reserved for you, the user, to inject your own graphics, controls, inputs & outputs, as well as your algorithm logic.\nLet’s demonstrate that functionality by injecting some UI, and the server code to handle the backend, into this base ShinyBroker app.\n\nStop the running instance of the ShinyBroker app and modify your code as shown below:\n\n\nimport shinybroker as sb\nfrom shiny import Inputs, Outputs, Session, ui, render\n\n\n# Some UI to add to the app\na_piece_of_new_ui = ui.div(\n    ui.input_text(\n        id='sb_example_text_in',\n        label='Example Input. Type something!'\n    ),\n    ui.output_code('sb_example_text_out')\n)\n\n\n# Server to support the new UI\n# Signature must always contain the following five parameters:\n#   input, output, session, ib_socket, and sb_rvs\ndef a_server_function(\n        input: Inputs, output: Outputs, session: Session, ib_socket, sb_rvs\n):\n    @render.code\n    def sb_example_text_out():\n        return f\"You entered '{input.sb_example_text_in()}'.\"\n\n\n# Create a ShinyBroker app with the new ui and server\napp = sb.sb_app(\n    a_piece_of_new_ui,\n    a_server_function,\n    host='127.0.0.1',\n    port=7497,\n    client_id=10742\n)\n\napp.run()\n\nHere, we have added two additional elements: a ui and a server(), just like we normally would when building a Shiny app with the Core syntax.\n\nui: We added a text input and a text output contained within a div\nserver: A Shiny server function just like a normal server function except that its signature includes a fourth argument – ib_socket – in addition to the usual three (input, output, session). The simple function in this example reads whatever text has been input by the user into the text_input, appends “You entered” to the beginning of it, and renders the text as output.\n\n\nRun the modified code above. Your app should now look something like the screenshot below: \n\nIf you can get that far, success! From this simple starting point you can build a trading algorithm that does just about anything. More usage examples that cover market data, orders, positions, and other topics will be treated in other tutorials and videos accessible on this site."
  },
  {
    "objectID": "reference/index.html",
    "href": "reference/index.html",
    "title": "Reference",
    "section": "",
    "text": "These objects are the building blocks that your application uses to work with important tasks like fetching market data or submitting a trade order.\n\n\n\nContract\nCreate a contract",
    "crumbs": [
      "Reference"
    ]
  },
  {
    "objectID": "reference/index.html#shinybroker-objects",
    "href": "reference/index.html#shinybroker-objects",
    "title": "Reference",
    "section": "",
    "text": "These objects are the building blocks that your application uses to work with important tasks like fetching market data or submitting a trade order.\n\n\n\nContract\nCreate a contract",
    "crumbs": [
      "Reference"
    ]
  }
]