# firstrade-api
A reverse-engineered python API to interact with the Firstrade Trading platform.
This is not an official api! This api's functionality may change at any time.
This api provides a means of buying and selling stocks through Firstrade. It uses the Session class from requests to get authorization cookies. The rest is done with reverse engineered requests to Firstrade's API.
In order to use Fractional shares you must accept the agreement on the website before using it in this API.
---
## Contribution
I am new to coding and new to open-source. I would love any help and suggestions!
## Disclaimer
I am not a financial advisor and not affiliated with Firstrade in any way. Use this tool at your own risk. I am not responsible for any losses or damages you may incur by using this project. This tool is provided as-is with no warranty.
## Setup
Install using pypi:
```
pip install firstrade
```
## Quikstart
The code below will:
- Login and print account info.
- Get a quote for 'INTC' and print out the information
- Place a dry run market order for 'INTC' on the first account in the `account_numbers` list
- Print out the order confirmation
- Contains a cancel order example
- Get an option Dates, Quotes, and Greeks
- Place a dry run option order
```python
from firstrade import account, order, symbols
# Create a session
ft_ss = account.FTSession(username="", password="", email = "", profile_path="")
need_code = ft_ss.login()
if need_code:
code = input("Please enter the pin sent to your email/phone: ")
ft_ss.login_two(code)
# Get account data
ft_accounts = account.FTAccountData(ft_ss)
if len(ft_accounts.account_numbers) < 1:
raise Exception("No accounts found or an error occured exiting...")
# Print ALL account data
print(ft_accounts.all_accounts)
# Print 1st account number.
print(ft_accounts.account_numbers[0])
# Print ALL accounts market values.
print(ft_accounts.account_balances)
# Get quote for INTC
quote = symbols.SymbolQuote(ft_ss, ft_accounts.account_numbers[0], "INTC")
print(f"Symbol: {quote.symbol}")
print(f"Tick: {quote.tick}")
print(f"Exchange: {quote.exchange}")
print(f"Bid: {quote.bid}")
print(f"Ask: {quote.ask}")
print(f"Last: {quote.last}")
print(f"Bid Size: {quote.bid_size}")
print(f"Ask Size: {quote.ask_size}")
print(f"Last Size: {quote.last_size}")
print(f"Bid MMID: {quote.bid_mmid}")
print(f"Ask MMID: {quote.ask_mmid}")
print(f"Last MMID: {quote.last_mmid}")
print(f"Change: {quote.change}")
print(f"High: {quote.high}")
print(f"Low: {quote.low}")
print(f"Change Color: {quote.change_color}")
print(f"Volume: {quote.volume}")
print(f"Quote Time: {quote.quote_time}")
print(f"Last Trade Time: {quote.last_trade_time}")
print(f"Real Time: {quote.realtime}")
print(f"Fractional: {quote.is_fractional}")
print(f"Company Name: {quote.company_name}")
# Get positions and print them out for an account.
positions = ft_accounts.get_positions(account=ft_accounts.account_numbers[1])
print(positions)
for item in positions["items"]:
print(
f"Quantity {item["quantity"]} of security {item["symbol"]} held in account {ft_accounts.account_numbers[1]}"
)
# Get account history (past 200)
history = ft_accounts.get_account_history(account=ft_accounts.account_numbers[0])
for item in history["items"]:
print(f"Transaction: {item["symbol"]} on {item["report_date"]} for {item["amount"]}.")
# Create an order object.
ft_order = order.Order(ft_ss)
# Place dry run order and print out order confirmation data.
order_conf = ft_order.place_order(
ft_accounts.account_numbers[0],
symbol="INTC",
price_type=order.PriceType.LIMIT,
order_type=order.OrderType.BUY,
duration=order.Duration.DAY,
quantity=1,
dry_run=True,
)
print(order_conf)
if "order_id" not in order_conf["result"]:
print("Dry run complete.")
print(order_conf["result"])
else:
print("Order placed successfully.")
print(f"Order ID: {order_conf["result"]["order_id"]}.")
print(f"Order State: {order_conf["result"]["state"]}.")
# Cancel placed order
# cancel = ft_accounts.cancel_order(order_conf['result']["order_id"])
# if cancel["result"]["result"] == "success":
# print("Order cancelled successfully.")
# print(cancel)
# Check orders
recent_orders = ft_accounts.get_orders(ft_accounts.account_numbers[0])
print(recent_orders)
#Get option dates
option_first = symbols.OptionQuote(ft_ss, "INTC")
for item in option_first.option_dates["items"]:
print(f"Expiration Date: {item["exp_date"]} Days Left: {item["day_left"]} Expiration Type: {item["exp_type"]}")
# Get option quote
option_quote = option_first.get_option_quote("INTC", option_first.option_dates["items"][0]["exp_date"])
print(option_quote)
# Get option greeks
option_greeks = option_first.get_greek_options("INTC", option_first.option_dates["items"][0]["exp_date"])
print(option_greeks)
print(f"Placing dry option order for {option_quote["items"][0]["opt_symbol"]} with a price of {option_quote["items"][0]["ask"]}.")
print("Symbol readable ticker 'INTC'")
# Place dry option order
option_order = ft_order.place_option_order(
account=ft_accounts.account_numbers[0],
option_symbol=option_quote["items"][0]["opt_symbol"],
order_type=order.OrderType.BUY_OPTION,
price_type=order.PriceType.MARKET,
duration=order.Duration.DAY,
contracts=1,
dry_run=True,
)
print(option_order)
# Delete cookies
ft_ss.delete_cookies()
```
`You can also find this code in test.py`
---
## Implemented Features
- [x] Login (With all 2FA methods now supported!)
- [x] Get Quotes
- [x] Get Account Data
- [x] Place Orders and Receive order confirmation
- [x] Get Currently Held Positions
- [x] Fractional Trading support (thanks to @jiak94)
- [x] Check on placed order status. (thanks to @Cfomodz)
- [x] Cancel placed orders
- [x] Options (Orders, Quotes, Greeks)
- [x] Order History
## TO DO
- [ ] Test options fully
- [ ] Give me some Ideas!
## Options
### I am very new to options trading and have not fully tested this feature.
Please:
- USE THIS FEATURE LIKE IT IS A ALPHA/BETA
- PUT IN A GITHUB ISSUE IF YOU FIND ANY PROBLEMS
## If you would like to support me, you can do so here:
[![GitHub Sponsors](https://img.shields.io/github/sponsors/maxxrk?style=social)](https://github.com/sponsors/maxxrk)
Raw data
{
"_id": null,
"home_page": "https://github.com/MaxxRK/firstrade-api",
"name": "firstrade",
"maintainer": null,
"docs_url": null,
"requires_python": null,
"maintainer_email": null,
"keywords": "FIRSTRADE, API",
"author": "MaxxRK",
"author_email": "maxxrk@pm.me",
"download_url": "https://files.pythonhosted.org/packages/2e/04/3ecdd514379c842e88e55948e417d5c9ccfc1cf06d4d5e1bd8344521daac/firstrade-0.0.30.tar.gz",
"platform": null,
"description": "# firstrade-api\n\nA reverse-engineered python API to interact with the Firstrade Trading platform.\n\nThis is not an official api! This api's functionality may change at any time.\n\nThis api provides a means of buying and selling stocks through Firstrade. It uses the Session class from requests to get authorization cookies. The rest is done with reverse engineered requests to Firstrade's API.\n\nIn order to use Fractional shares you must accept the agreement on the website before using it in this API.\n\n---\n\n## Contribution\n\nI am new to coding and new to open-source. I would love any help and suggestions!\n\n## Disclaimer\nI am not a financial advisor and not affiliated with Firstrade in any way. Use this tool at your own risk. I am not responsible for any losses or damages you may incur by using this project. This tool is provided as-is with no warranty.\n\n## Setup\n\nInstall using pypi:\n\n```\npip install firstrade\n```\n\n## Quikstart\n\nThe code below will:\n- Login and print account info.\n- Get a quote for 'INTC' and print out the information\n- Place a dry run market order for 'INTC' on the first account in the `account_numbers` list\n- Print out the order confirmation\n- Contains a cancel order example\n- Get an option Dates, Quotes, and Greeks\n- Place a dry run option order\n\n```python\nfrom firstrade import account, order, symbols\n\n# Create a session\nft_ss = account.FTSession(username=\"\", password=\"\", email = \"\", profile_path=\"\")\nneed_code = ft_ss.login()\nif need_code:\n code = input(\"Please enter the pin sent to your email/phone: \")\n ft_ss.login_two(code)\n\n# Get account data\nft_accounts = account.FTAccountData(ft_ss)\nif len(ft_accounts.account_numbers) < 1:\n raise Exception(\"No accounts found or an error occured exiting...\")\n\n# Print ALL account data\nprint(ft_accounts.all_accounts)\n\n# Print 1st account number.\nprint(ft_accounts.account_numbers[0])\n\n# Print ALL accounts market values.\nprint(ft_accounts.account_balances)\n\n# Get quote for INTC\nquote = symbols.SymbolQuote(ft_ss, ft_accounts.account_numbers[0], \"INTC\")\nprint(f\"Symbol: {quote.symbol}\")\nprint(f\"Tick: {quote.tick}\")\nprint(f\"Exchange: {quote.exchange}\")\nprint(f\"Bid: {quote.bid}\")\nprint(f\"Ask: {quote.ask}\")\nprint(f\"Last: {quote.last}\")\nprint(f\"Bid Size: {quote.bid_size}\")\nprint(f\"Ask Size: {quote.ask_size}\")\nprint(f\"Last Size: {quote.last_size}\")\nprint(f\"Bid MMID: {quote.bid_mmid}\")\nprint(f\"Ask MMID: {quote.ask_mmid}\")\nprint(f\"Last MMID: {quote.last_mmid}\")\nprint(f\"Change: {quote.change}\")\nprint(f\"High: {quote.high}\")\nprint(f\"Low: {quote.low}\")\nprint(f\"Change Color: {quote.change_color}\")\nprint(f\"Volume: {quote.volume}\")\nprint(f\"Quote Time: {quote.quote_time}\")\nprint(f\"Last Trade Time: {quote.last_trade_time}\")\nprint(f\"Real Time: {quote.realtime}\")\nprint(f\"Fractional: {quote.is_fractional}\")\nprint(f\"Company Name: {quote.company_name}\")\n\n# Get positions and print them out for an account.\npositions = ft_accounts.get_positions(account=ft_accounts.account_numbers[1])\nprint(positions)\nfor item in positions[\"items\"]:\n print(\n f\"Quantity {item[\"quantity\"]} of security {item[\"symbol\"]} held in account {ft_accounts.account_numbers[1]}\"\n )\n\n# Get account history (past 200)\nhistory = ft_accounts.get_account_history(account=ft_accounts.account_numbers[0])\nfor item in history[\"items\"]:\n print(f\"Transaction: {item[\"symbol\"]} on {item[\"report_date\"]} for {item[\"amount\"]}.\")\n\n\n# Create an order object.\nft_order = order.Order(ft_ss)\n\n# Place dry run order and print out order confirmation data.\norder_conf = ft_order.place_order(\n ft_accounts.account_numbers[0],\n symbol=\"INTC\",\n price_type=order.PriceType.LIMIT,\n order_type=order.OrderType.BUY,\n duration=order.Duration.DAY,\n quantity=1,\n dry_run=True,\n)\n\nprint(order_conf)\n\nif \"order_id\" not in order_conf[\"result\"]:\n print(\"Dry run complete.\")\n print(order_conf[\"result\"])\nelse:\n print(\"Order placed successfully.\")\n print(f\"Order ID: {order_conf[\"result\"][\"order_id\"]}.\")\n print(f\"Order State: {order_conf[\"result\"][\"state\"]}.\")\n\n# Cancel placed order\n# cancel = ft_accounts.cancel_order(order_conf['result'][\"order_id\"])\n# if cancel[\"result\"][\"result\"] == \"success\":\n # print(\"Order cancelled successfully.\")\n# print(cancel)\n\n# Check orders\nrecent_orders = ft_accounts.get_orders(ft_accounts.account_numbers[0])\nprint(recent_orders)\n\n#Get option dates\noption_first = symbols.OptionQuote(ft_ss, \"INTC\")\nfor item in option_first.option_dates[\"items\"]:\n print(f\"Expiration Date: {item[\"exp_date\"]} Days Left: {item[\"day_left\"]} Expiration Type: {item[\"exp_type\"]}\")\n\n# Get option quote\noption_quote = option_first.get_option_quote(\"INTC\", option_first.option_dates[\"items\"][0][\"exp_date\"])\nprint(option_quote)\n\n# Get option greeks\noption_greeks = option_first.get_greek_options(\"INTC\", option_first.option_dates[\"items\"][0][\"exp_date\"])\nprint(option_greeks)\n\nprint(f\"Placing dry option order for {option_quote[\"items\"][0][\"opt_symbol\"]} with a price of {option_quote[\"items\"][0][\"ask\"]}.\")\nprint(\"Symbol readable ticker 'INTC'\")\n\n# Place dry option order\noption_order = ft_order.place_option_order(\n account=ft_accounts.account_numbers[0],\n option_symbol=option_quote[\"items\"][0][\"opt_symbol\"],\n order_type=order.OrderType.BUY_OPTION,\n price_type=order.PriceType.MARKET,\n duration=order.Duration.DAY,\n contracts=1,\n dry_run=True,\n)\n\nprint(option_order)\n\n# Delete cookies\nft_ss.delete_cookies()\n```\n\n`You can also find this code in test.py`\n\n---\n\n## Implemented Features\n\n- [x] Login (With all 2FA methods now supported!) \n- [x] Get Quotes\n- [x] Get Account Data\n- [x] Place Orders and Receive order confirmation\n- [x] Get Currently Held Positions\n- [x] Fractional Trading support (thanks to @jiak94)\n- [x] Check on placed order status. (thanks to @Cfomodz)\n- [x] Cancel placed orders\n- [x] Options (Orders, Quotes, Greeks)\n- [x] Order History\n\n## TO DO\n\n- [ ] Test options fully\n- [ ] Give me some Ideas!\n\n## Options\n\n### I am very new to options trading and have not fully tested this feature.\n\nPlease:\n- USE THIS FEATURE LIKE IT IS A ALPHA/BETA\n- PUT IN A GITHUB ISSUE IF YOU FIND ANY PROBLEMS\n \n## If you would like to support me, you can do so here:\n[![GitHub Sponsors](https://img.shields.io/github/sponsors/maxxrk?style=social)](https://github.com/sponsors/maxxrk)\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "An unofficial API for Firstrade",
"version": "0.0.30",
"project_urls": {
"Download": "https://github.com/MaxxRK/firstrade-api/archive/refs/tags/0030.tar.gz",
"Homepage": "https://github.com/MaxxRK/firstrade-api"
},
"split_keywords": [
"firstrade",
" api"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "9acf02b8f8a4f1aa9ccdc51b9d9cab1e749f3e6e06c6fe96229f7b9a1089e5dd",
"md5": "e72baa62f7f821391a2dc62a54134dfe",
"sha256": "5ba785aa0706dc06806a24ab8d653f57f26af1962b8700fa3931c62b471cec85"
},
"downloads": -1,
"filename": "firstrade-0.0.30-py3-none-any.whl",
"has_sig": false,
"md5_digest": "e72baa62f7f821391a2dc62a54134dfe",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": null,
"size": 12916,
"upload_time": "2024-08-18T20:50:54",
"upload_time_iso_8601": "2024-08-18T20:50:54.533027Z",
"url": "https://files.pythonhosted.org/packages/9a/cf/02b8f8a4f1aa9ccdc51b9d9cab1e749f3e6e06c6fe96229f7b9a1089e5dd/firstrade-0.0.30-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "2e043ecdd514379c842e88e55948e417d5c9ccfc1cf06d4d5e1bd8344521daac",
"md5": "d2d5627e63283e39ee4d1e96535658b7",
"sha256": "1beed88f1f11abb6981ad099789d76225976f76cc11d1ab2a0dc9981535fd7d0"
},
"downloads": -1,
"filename": "firstrade-0.0.30.tar.gz",
"has_sig": false,
"md5_digest": "d2d5627e63283e39ee4d1e96535658b7",
"packagetype": "sdist",
"python_version": "source",
"requires_python": null,
"size": 13878,
"upload_time": "2024-08-18T20:50:55",
"upload_time_iso_8601": "2024-08-18T20:50:55.413977Z",
"url": "https://files.pythonhosted.org/packages/2e/04/3ecdd514379c842e88e55948e417d5c9ccfc1cf06d4d5e1bd8344521daac/firstrade-0.0.30.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-08-18 20:50:55",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "MaxxRK",
"github_project": "firstrade-api",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "firstrade"
}