Tuesday, August 22, 2023

Kotlin - Convert list of String to Map with count of each element as value

 

Kotlin Code to transform List into Map with list elements as Key and value as count of each element. Map contains only unique keys.

 



fun main() {
    countListElements(listOf("Apple", "orange", "mango", "orange"))
}

fun countListElements(fruits: List String>) {
    val fruitMap = fruits.groupingBy { it }.eachCount()
    print(fruitMap)
}

 

Friday, April 21, 2023

Algotrading: Exit Positions in Fyers API

Example code snippet for exiting positions in Fyers API


Code:


if __name__ == '__main__':
    token = get_auth_code()
    fyers = fyersModel.FyersModel(client_id=client_id, token=token, log_path='/tmp/')
    print(fyers.positions())

    data = [{"id": "NSE:BANKNIFTY23APR42900CE-MARGIN"}, {"id": "NSE:BANKNIFTY23APR41300PE-MARGIN"}]
    pos_res = fyers.exit_positions(data)

    print(pos_res)

    pos_res = fyers.exit_positions()

    print(pos_res)
  

Please copy the code for get_auth_code() from previous blogpost for Fyers V2 login

 

Happy trading. Enjoy.

Saturday, April 15, 2023

Get Trading holiday list using Python

 

Code to  get the list of NSE trading holidays, to use in your algo trading.




import json
from datetime import datetime

import requests

if __name__ == '__main__':
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/109.0',
        'Accept': '*/*',
        'Accept-Language': 'en-US,en;q=0.5',
        # 'Accept-Encoding': 'gzip, deflate, br',
        'Connection': 'keep-alive',
        'Referer': 'https://www.nseindia.com/resources/exchange-communication-holidays',

        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
    }

    params = {
        'type': 'trading',
    }

    response = requests.get('https://www.nseindia.com/api/holiday-master', params=params, headers=headers)

    jsonResponse = response.json()

    for record in jsonResponse['FO']:
        # print(record["tradingDate"])
        print(datetime.strptime(record["tradingDate"], '%d-%b-%Y').strftime('%d/%m/%Y'))

    with open('data.json', 'w') as f:
        json.dump(jsonResponse['FO'], f, ensure_ascii=False, indent=4)

Happy Coding.