├── Formulas ├── AutoTraderWeb │ ├── Buttons │ │ ├── at-buy-sell-buttons-bo.afl │ │ ├── at-buy-sell-buttons-co-pct.afl │ │ ├── at-buy-sell-buttons-co.afl │ │ ├── at-buy-sell-buttons-hardcode.afl │ │ ├── at-buy-sell-buttons-symbol-mapping.afl │ │ ├── at-buy-sell-buttons-two-legs.afl │ │ └── at-buy-sell-buttons.afl │ └── General │ │ ├── MultiAccount │ │ ├── at-ema-crossover-multi-account.afl │ │ └── at-supertrend-multi-account.afl │ │ ├── at-ema-buy-sell-short-cover.afl │ │ ├── at-ema-crossover.afl │ │ ├── at-supertrend-scanner.afl │ │ ├── at-supertrend.afl │ │ └── at-target-sl-without-bo.afl └── Include │ ├── autotrader-api.afl │ ├── autotrader-button.afl │ ├── autotrader-defaults.afl │ ├── autotrader-ipc.afl │ ├── autotrader-next-bar.afl │ ├── autotrader-post-util.afl │ ├── autotrader-pre-util.afl │ ├── autotrader-quantity-mapping.afl │ ├── autotrader-square-off.afl │ ├── autotrader-symbol-mapping.afl │ ├── autotrader.afl │ ├── conversion-util.afl │ ├── file-util.afl │ ├── logs-util.afl │ ├── misc-util.afl │ └── text-util.afl ├── LICENSE └── README.md /Formulas/AutoTraderWeb/Buttons/at-buy-sell-buttons-bo.afl: -------------------------------------------------------------------------------- 1 | /** 2 | * AmiBroker BUY/SELL buttons Bracket Order example. 3 | * You need to set appropriate values in chart parameters. 4 | * 5 | * Button Article: https://stocksdeveloper.in/amibroker-multi-account-button-trading/ 6 | * User Guide: https://stocksdeveloper.in/documentation/index/ 7 | * API Docs: https://stocksdeveloper.in/documentation/api/ 8 | * Symbol Search: https://web.stocksdeveloper.in/instrument 9 | * 10 | * Author - Stocks Developer 11 | */ 12 | 13 | #include 14 | #include 15 | 16 | _SECTION_BEGIN("Bracket Order"); 17 | 18 | TARGET = Param("Target (absolute)", 1, 1, 1000, 1); 19 | STOPLOSS = Param("Stoploss (absolute)", 1, 1, 1000, 1); 20 | TRAILING_STOPLOSS = Param("Trailing Stoploss (absolute)", 0, 0, 100, 1); 21 | BUFFER = Param("Make BO behave like a market order", 0, 0, 100, 1); 22 | 23 | _SECTION_END(); 24 | 25 | // Following code adds buttons to the screen 26 | Column_Begin( "1" ); 27 | BuyCommand = TriggerCell( "BUY", colorBrightGreen, colorAqua, colorBlack); 28 | Column_End( ); 29 | 30 | Column_Begin( "2" ); 31 | SellCommand = TriggerCell( "SELL", colorRed, colorLightOrange, colorBlack); 32 | Column_End( ); 33 | 34 | Column_Begin( "3" ); 35 | SellCommand = TriggerCell( "Square Off", colorYellow, colorGold, colorBlack); 36 | Column_End( ); 37 | 38 | // Get co-ordinates 39 | ClickCoordinates = Nz(StaticVarGet("ClickCoordinates")); 40 | 41 | // Take action based on the button placed by user 42 | switch( ClickCoordinates ) 43 | { 44 | case 101: 45 | // Place buy orders when user clicks on BUY button 46 | livePrice = LastValue(C); 47 | orderPrice = livePrice + BUFFER; 48 | 49 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 50 | message = "Placing a BUY limit bracket order, with price = " 51 | + orderPrice + ", target = " + TARGET 52 | + ", stoploss = " + STOPLOSS 53 | + "trailing stoploss = " + TRAILING_STOPLOSS; 54 | logDebug(message); 55 | _TRACE(message); 56 | 57 | // You can write any of AutoTrader Web API functions here 58 | placeBracketOrder(acc, 59 | AT_EXCHANGE, AT_SYMBOL, "BUY", 60 | "LIMIT", AT_QUANTITY, orderPrice, defaultTriggerPrice(), 61 | TARGET, STOPLOSS, TRAILING_STOPLOSS, False); 62 | } 63 | break; 64 | 65 | case 201: 66 | // Place sell orders when user clicks on SELL button 67 | livePrice = LastValue(C); 68 | orderPrice = livePrice - BUFFER; 69 | 70 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 71 | message = "Placing a SELL limit bracket order, with price = " 72 | + orderPrice + ", target = " + TARGET 73 | + ", stoploss = " + STOPLOSS 74 | + "trailing stoploss = " + TRAILING_STOPLOSS; 75 | logDebug(message); 76 | _TRACE(message); 77 | 78 | // You can write any of AutoTrader Web API functions here 79 | placeBracketOrder(acc, 80 | AT_EXCHANGE, AT_SYMBOL, "SELL", 81 | "LIMIT", AT_QUANTITY, orderPrice, defaultTriggerPrice(), 82 | TARGET, STOPLOSS, TRAILING_STOPLOSS, False); 83 | } 84 | break; 85 | 86 | case 301: 87 | // Place a square off request when user clicks on Square Off button 88 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 89 | message = "Sending square-off position request sent for account [" + (iter + 1) + "] : " + acc 90 | + ", Position : " + AT_SYMBOL; 91 | logDebug(message); 92 | _TRACE(message); 93 | 94 | // You can write any of AutoTrader Web API functions here 95 | positionType = calcPositionType(AT_VARIETY_BO, AT_PRODUCT_TYPE); 96 | squareOffPosition(acc, "NET", positionType, AT_EXCHANGE, AT_SYMBOL); 97 | } 98 | break; 99 | } -------------------------------------------------------------------------------- /Formulas/AutoTraderWeb/Buttons/at-buy-sell-buttons-co-pct.afl: -------------------------------------------------------------------------------- 1 | /** 2 | * AmiBroker BUY/SELL buttons Cover Order example. 3 | * Stoploss is accepted as a percentage of live price. 4 | * You need to set appropriate values in chart parameters. 5 | * 6 | * Button Article: https://stocksdeveloper.in/amibroker-multi-account-button-trading/ 7 | * User Guide: https://stocksdeveloper.in/documentation/index/ 8 | * API Docs: https://stocksdeveloper.in/documentation/api/ 9 | * Symbol Search: https://web.stocksdeveloper.in/instrument 10 | * 11 | * Author - Stocks Developer 12 | */ 13 | 14 | #include 15 | #include 16 | 17 | _SECTION_BEGIN("AutoTrader Buttons"); 18 | 19 | STOPLOSS = Param("Stoploss % (percentage)", 1, 1, 100, 1); 20 | 21 | _SECTION_END(); 22 | 23 | 24 | // Following code adds buttons to the screen 25 | Column_Begin( "1" ); 26 | BuyCommand = TriggerCell( "BUY", colorBrightGreen, colorAqua, colorBlack); 27 | Column_End( ); 28 | 29 | Column_Begin( "2" ); 30 | SellCommand = TriggerCell( "SELL", colorRed, colorLightOrange, colorBlack); 31 | Column_End( ); 32 | 33 | Column_Begin( "3" ); 34 | SellCommand = TriggerCell( "Square Off", colorYellow, colorGold, colorBlack); 35 | Column_End( ); 36 | 37 | // Get co-ordinates 38 | ClickCoordinates = Nz(StaticVarGet("ClickCoordinates")); 39 | 40 | // Take action based on the button placed by user 41 | switch( ClickCoordinates ) 42 | { 43 | case 101: 44 | // Place buy orders when user clicks on BUY button 45 | livePrice = LastValue(C); 46 | stoplossTriggerPrice = livePrice * (1 - (STOPLOSS / 100)); 47 | 48 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 49 | message = "Placing a BUY market cover order, with a stoploss trigger price = " 50 | + stoplossTriggerPrice; 51 | logDebug(message); 52 | _TRACE(message); 53 | 54 | // You can write any of AutoTrader Web API functions here 55 | placeCoverOrder(acc, AT_EXCHANGE, 56 | AT_SYMBOL, "BUY", "MARKET", AT_QUANTITY, 57 | 0, stoplossTriggerPrice, False); 58 | } 59 | break; 60 | 61 | case 201: 62 | // Place sell orders when user clicks on SELL button 63 | livePrice = LastValue(C); 64 | stoplossTriggerPrice = livePrice * (1 + (STOPLOSS / 100)); 65 | 66 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 67 | message = "Placing a SELL market cover order, with a stoploss trigger price = " 68 | + stoplossTriggerPrice; 69 | logDebug(message); 70 | _TRACE(message); 71 | 72 | // You can write any of AutoTrader Web API functions here 73 | placeCoverOrder(acc, AT_EXCHANGE, 74 | AT_SYMBOL, "SELL", "MARKET", AT_QUANTITY, 75 | 0, stoplossTriggerPrice, False); 76 | } 77 | break; 78 | 79 | case 301: 80 | // Place a square off request when user clicks on Square Off button 81 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 82 | message = "Sending square-off position request sent for account [" + (iter + 1) + "] : " + acc 83 | + ", Position : " + AT_SYMBOL; 84 | logDebug(message); 85 | _TRACE(message); 86 | 87 | // You can write any of AutoTrader Web API functions here 88 | positionType = calcPositionType(AT_VARIETY_CO, AT_PRODUCT_TYPE); 89 | squareOffPosition(acc, "NET", positionType, AT_EXCHANGE, AT_SYMBOL); 90 | } 91 | break; 92 | } -------------------------------------------------------------------------------- /Formulas/AutoTraderWeb/Buttons/at-buy-sell-buttons-co.afl: -------------------------------------------------------------------------------- 1 | /** 2 | * AmiBroker BUY/SELL buttons Cover Order example. 3 | * Stoploss is accepted as an absolute value. 4 | * You need to set appropriate values in chart parameters. 5 | * 6 | * Button Article: https://stocksdeveloper.in/amibroker-multi-account-button-trading/ 7 | * User Guide: https://stocksdeveloper.in/documentation/index/ 8 | * API Docs: https://stocksdeveloper.in/documentation/api/ 9 | * Symbol Search: https://web.stocksdeveloper.in/instrument 10 | * 11 | * Author - Stocks Developer 12 | */ 13 | 14 | #include 15 | #include 16 | 17 | _SECTION_BEGIN("Cover Order"); 18 | 19 | STOPLOSS = Param("Stoploss (absolute)", 1, 1, 1000, 1); 20 | 21 | _SECTION_END(); 22 | 23 | // Following code adds buttons to the screen 24 | Column_Begin( "1" ); 25 | BuyCommand = TriggerCell( "BUY", colorBrightGreen, colorAqua, colorBlack); 26 | Column_End( ); 27 | 28 | Column_Begin( "2" ); 29 | SellCommand = TriggerCell( "SELL", colorRed, colorLightOrange, colorBlack); 30 | Column_End( ); 31 | 32 | Column_Begin( "3" ); 33 | SellCommand = TriggerCell( "Square Off", colorYellow, colorGold, colorBlack); 34 | Column_End( ); 35 | 36 | // Get co-ordinates 37 | ClickCoordinates = Nz(StaticVarGet("ClickCoordinates")); 38 | 39 | // Take action based on the button placed by user 40 | switch( ClickCoordinates ) 41 | { 42 | case 101: 43 | // Place buy orders when user clicks on BUY button 44 | livePrice = LastValue(C); 45 | stoplossTriggerPrice = livePrice - STOPLOSS; 46 | 47 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 48 | message = "Placing a BUY market cover order, with a stoploss trigger price = " 49 | + stoplossTriggerPrice; 50 | logDebug(message); 51 | _TRACE(message); 52 | 53 | // You can write any of AutoTrader Web API functions here 54 | placeCoverOrder(acc, AT_EXCHANGE, 55 | AT_SYMBOL, "BUY", "MARKET", AT_QUANTITY, 56 | 0, stoplossTriggerPrice, False); 57 | } 58 | break; 59 | 60 | case 201: 61 | // Place sell orders when user clicks on SELL button 62 | livePrice = LastValue(C); 63 | stoplossTriggerPrice = livePrice + STOPLOSS; 64 | 65 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 66 | message = "Placing a SELL market cover order, with a stoploss trigger price = " 67 | + stoplossTriggerPrice; 68 | logDebug(message); 69 | _TRACE(message); 70 | 71 | // You can write any of AutoTrader Web API functions here 72 | placeCoverOrder(acc, AT_EXCHANGE, 73 | AT_SYMBOL, "SELL", "MARKET", AT_QUANTITY, 74 | 0, stoplossTriggerPrice, False); 75 | } 76 | break; 77 | 78 | case 301: 79 | // Place a square off request when user clicks on Square Off button 80 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 81 | message = "Sending square-off position request sent for account [" + (iter + 1) + "] : " + acc 82 | + ", Position : " + AT_SYMBOL; 83 | logDebug(message); 84 | _TRACE(message); 85 | 86 | // You can write any of AutoTrader Web API functions here 87 | positionType = calcPositionType(AT_VARIETY_CO, AT_PRODUCT_TYPE); 88 | squareOffPosition(acc, "NET", positionType, AT_EXCHANGE, AT_SYMBOL); 89 | } 90 | break; 91 | } -------------------------------------------------------------------------------- /Formulas/AutoTraderWeb/Buttons/at-buy-sell-buttons-hardcode.afl: -------------------------------------------------------------------------------- 1 | /** 2 | * AmiBroker BUY/SELL buttons Regular Order example with hardcoded values. 3 | * This example does not make use of chart parameters except account numbers. 4 | * It shows how you can directly hardcode the values in API function calls. 5 | * 6 | * Button Article: https://stocksdeveloper.in/amibroker-multi-account-button-trading/ 7 | * User Guide: https://stocksdeveloper.in/documentation/index/ 8 | * API Docs: https://stocksdeveloper.in/documentation/api/ 9 | * Symbol Search: https://web.stocksdeveloper.in/instrument 10 | * 11 | * Author - Stocks Developer 12 | */ 13 | 14 | #include 15 | #include 16 | 17 | // Following code adds buttons to the screen 18 | Column_Begin( "1" ); 19 | BuyCommand = TriggerCell( "BUY", colorBrightGreen, colorAqua, colorBlack); 20 | Column_End( ); 21 | 22 | Column_Begin( "2" ); 23 | SellCommand = TriggerCell( "SELL", colorRed, colorLightOrange, colorBlack); 24 | Column_End( ); 25 | 26 | Column_Begin( "3" ); 27 | SellCommand = TriggerCell( "Square Off", colorYellow, colorGold, colorBlack); 28 | Column_End( ); 29 | 30 | // Get co-ordinates 31 | ClickCoordinates = Nz(StaticVarGet("ClickCoordinates")); 32 | 33 | // Take action based on the button placed by user 34 | switch( ClickCoordinates ) 35 | { 36 | case 101: 37 | // Place buy orders when user clicks on BUY button 38 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 39 | message = "Placing BUY order for account [" + (iter + 1) + "] : " + acc; 40 | logDebug(message); 41 | _TRACE(message); 42 | 43 | // You can write any of AutoTrader Web API functions here 44 | placeOrder(acc, "NSE", "BANKNIFTY_29-OCT-2020_FUT", "BUY", "MARKET", 45 | "INTRADAY", 25, 0, defaultTriggerPrice(), False); 46 | } 47 | break; 48 | 49 | case 201: 50 | // Place sell orders when user clicks on SELL button 51 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 52 | message = "Placing SELL order for account [" + (iter + 1) + "] : " + acc; 53 | logDebug(message); 54 | _TRACE(message); 55 | 56 | // You can write any of AutoTrader Web API functions here 57 | placeOrder(acc, "NSE", "BANKNIFTY_29-OCT-2020_FUT", "SELL", "MARKET", 58 | "INTRADAY", 25, 0, defaultTriggerPrice(), False); 59 | } 60 | break; 61 | 62 | case 301: 63 | // Place a square off request when user clicks on Square Off button 64 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 65 | message = "Sending square-off position request sent for account [" + (iter + 1) + "] : " + acc 66 | + ", Position : " + AT_SYMBOL; 67 | logDebug(message); 68 | _TRACE(message); 69 | 70 | // You can write any of AutoTrader Web API functions here 71 | positionType = calcPositionType(AT_VARIETY_REGULAR, "INTRADAY"); 72 | squareOffPosition(acc, "NET", positionType, "NSE", "BANKNIFTY_29-OCT-2020_FUT"); 73 | } 74 | break; 75 | } -------------------------------------------------------------------------------- /Formulas/AutoTraderWeb/Buttons/at-buy-sell-buttons-symbol-mapping.afl: -------------------------------------------------------------------------------- 1 | /** 2 | * AmiBroker BUY/SELL buttons Regular Order example (Quantity mapping file). 3 | * 4 | * Quantity mapping file: 5 | * - Prepare the mapping file, as describe in Scanner section on following link: 6 | * - https://stocksdeveloper.in/documentation/client-setup/amibroker-library#scanner 7 | * - Go to chart parameters 8 | * - Set "Use symbol mapping file" to ON 9 | * - Give the path of your quantity mapping file 10 | * 11 | * You need to set appropriate values in chart parameters. 12 | * 13 | * Button Article: https://stocksdeveloper.in/amibroker-multi-account-button-trading/ 14 | * User Guide: https://stocksdeveloper.in/documentation/index/ 15 | * API Docs: https://stocksdeveloper.in/documentation/api/ 16 | * Symbol Search: https://web.stocksdeveloper.in/instrument 17 | * 18 | * Author - Stocks Developer 19 | */ 20 | 21 | #include 22 | #include 23 | #include 24 | 25 | 26 | // Following code adds buttons to the screen 27 | Column_Begin( "1" ); 28 | BuyCommand = TriggerCell( "BUY", colorBrightGreen, colorAqua, colorBlack); 29 | Column_End( ); 30 | 31 | Column_Begin( "2" ); 32 | SellCommand = TriggerCell( "SELL", colorRed, colorLightOrange, colorBlack); 33 | Column_End( ); 34 | 35 | Column_Begin( "3" ); 36 | SellCommand = TriggerCell( "Square Off", colorYellow, colorGold, colorBlack); 37 | Column_End( ); 38 | 39 | // Get co-ordinates 40 | ClickCoordinates = Nz(StaticVarGet("ClickCoordinates")); 41 | 42 | // Take action based on the button placed by user 43 | switch( ClickCoordinates ) 44 | { 45 | case 101: 46 | // Place buy orders when user clicks on BUY button 47 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 48 | message = "Placing BUY order for account [" + (iter + 1) + "] : " + acc; 49 | logDebug(message); 50 | _TRACE(message); 51 | 52 | // You can write any of AutoTrader Web API functions here 53 | placeOrder(acc, AT_EXCHANGE, getSymbol(Name()), "BUY", "MARKET", 54 | AT_PRODUCT_TYPE, AT_QUANTITY, 0, defaultTriggerPrice(), True); 55 | } 56 | break; 57 | 58 | case 201: 59 | // Place sell orders when user clicks on SELL button 60 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 61 | message = "Placing SELL order for account [" + (iter + 1) + "] : " + acc; 62 | logDebug(message); 63 | _TRACE(message); 64 | 65 | // You can write any of AutoTrader Web API functions here 66 | placeOrder(acc, AT_EXCHANGE, getSymbol(Name()), "SELL", "MARKET", 67 | AT_PRODUCT_TYPE, AT_QUANTITY, 0, defaultTriggerPrice(), False); 68 | } 69 | break; 70 | 71 | case 301: 72 | // Place a square off request when user clicks on Square Off button 73 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 74 | message = "Sending square-off position request sent for account [" + (iter + 1) + "] : " + acc 75 | + ", Position : " + getSymbol(Name()); 76 | logDebug(message); 77 | _TRACE(message); 78 | 79 | // You can write any of AutoTrader Web API functions here 80 | positionType = calcPositionType(AT_VARIETY_REGULAR, AT_PRODUCT_TYPE); 81 | squareOffPosition(acc, "NET", positionType, AT_EXCHANGE, getSymbol(Name())); 82 | } 83 | break; 84 | 85 | } -------------------------------------------------------------------------------- /Formulas/AutoTraderWeb/Buttons/at-buy-sell-buttons-two-legs.afl: -------------------------------------------------------------------------------- 1 | /** 2 | * AmiBroker BUY/SELL buttons Regular Order example. 3 | * You need to set appropriate values in chart parameters. 4 | * 5 | * Button Article: https://stocksdeveloper.in/amibroker-multi-account-button-trading/ 6 | * User Guide: https://stocksdeveloper.in/documentation/index/ 7 | * API Docs: https://stocksdeveloper.in/documentation/api/ 8 | * Symbol Search: https://web.stocksdeveloper.in/instrument 9 | * 10 | * Author - Stocks Developer 11 | */ 12 | 13 | #include 14 | #include 15 | 16 | _SECTION_BEGIN("Two Legs Strategy"); 17 | 18 | LEG_ONE_SYMBOL = ParamStr("Leg One Symbol", Name()); 19 | LEG_TWO_SYMBOL = ParamStr("Leg Two Symbol", Name()); 20 | 21 | _SECTION_END(); 22 | 23 | 24 | // Following code adds buttons to the screen 25 | Column_Begin( "1" ); 26 | BuyCommand = TriggerCell( "BUY", colorBrightGreen, colorAqua, colorBlack); 27 | Column_End( ); 28 | 29 | Column_Begin( "2" ); 30 | SellCommand = TriggerCell( "SELL", colorRed, colorLightOrange, colorBlack); 31 | Column_End( ); 32 | 33 | Column_Begin( "3" ); 34 | SellCommand = TriggerCell( "Square Off", colorYellow, colorGold, colorBlack); 35 | Column_End( ); 36 | 37 | // Get co-ordinates 38 | ClickCoordinates = Nz(StaticVarGet("ClickCoordinates")); 39 | 40 | // Take action based on the button placed by user 41 | switch( ClickCoordinates ) 42 | { 43 | case 101: 44 | // Place buy orders when user clicks on BUY button 45 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 46 | message = "[LEG 1] Placing BUY order for account [" + (iter + 1) + "] : " + acc; 47 | logDebug(message); 48 | _TRACE(message); 49 | 50 | // You can write any of AutoTrader Web API functions here 51 | placeOrder(acc, AT_EXCHANGE, LEG_ONE_SYMBOL, "BUY", "MARKET", 52 | AT_PRODUCT_TYPE, AT_QUANTITY, 0, defaultTriggerPrice(), False); 53 | 54 | message = "[LEG 2] Placing BUY order for account [" + (iter + 1) + "] : " + acc; 55 | logDebug(message); 56 | _TRACE(message); 57 | 58 | // You can write any of AutoTrader Web API functions here 59 | placeOrder(acc, AT_EXCHANGE, LEG_TWO_SYMBOL, "BUY", "MARKET", 60 | AT_PRODUCT_TYPE, AT_QUANTITY, 0, defaultTriggerPrice(), False); 61 | } 62 | break; 63 | 64 | case 201: 65 | // Place sell orders when user clicks on SELL button 66 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 67 | message = "[LEG 1] Placing SELL order for account [" + (iter + 1) + "] : " + acc; 68 | logDebug(message); 69 | _TRACE(message); 70 | 71 | // You can write any of AutoTrader Web API functions here 72 | placeOrder(acc, AT_EXCHANGE, LEG_ONE_SYMBOL, "SELL", "MARKET", 73 | AT_PRODUCT_TYPE, AT_QUANTITY, 0, defaultTriggerPrice(), False); 74 | 75 | message = "[LEG 2] Placing SELL order for account [" + (iter + 1) + "] : " + acc; 76 | logDebug(message); 77 | _TRACE(message); 78 | 79 | // You can write any of AutoTrader Web API functions here 80 | placeOrder(acc, AT_EXCHANGE, LEG_TWO_SYMBOL, "SELL", "MARKET", 81 | AT_PRODUCT_TYPE, AT_QUANTITY, 0, defaultTriggerPrice(), False); 82 | } 83 | break; 84 | 85 | case 301: 86 | // Place a square off request when user clicks on Square Off button 87 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 88 | message = "[LEG 1] Sending square-off position request sent for account [" + (iter + 1) + "] : " + acc 89 | + ", Position : " + LEG_ONE_SYMBOL; 90 | logDebug(message); 91 | _TRACE(message); 92 | 93 | // You can write any of AutoTrader Web API functions here 94 | positionType = calcPositionType(AT_VARIETY_REGULAR, AT_PRODUCT_TYPE); 95 | squareOffPosition(acc, "NET", positionType, AT_EXCHANGE, LEG_ONE_SYMBOL); 96 | 97 | message = "[LEG 2] Sending square-off position request sent for account [" + (iter + 1) + "] : " + acc 98 | + ", Position : " + LEG_TWO_SYMBOL; 99 | logDebug(message); 100 | _TRACE(message); 101 | 102 | // You can write any of AutoTrader Web API functions here 103 | positionType = calcPositionType(AT_VARIETY_REGULAR, AT_PRODUCT_TYPE); 104 | squareOffPosition(acc, "NET", positionType, AT_EXCHANGE, LEG_TWO_SYMBOL); 105 | } 106 | break; 107 | 108 | } -------------------------------------------------------------------------------- /Formulas/AutoTraderWeb/Buttons/at-buy-sell-buttons.afl: -------------------------------------------------------------------------------- 1 | /** 2 | * AmiBroker BUY/SELL buttons Regular Order example. 3 | * You need to set appropriate values in chart parameters. 4 | * 5 | * Button Article: https://stocksdeveloper.in/amibroker-multi-account-button-trading/ 6 | * User Guide: https://stocksdeveloper.in/documentation/index/ 7 | * API Docs: https://stocksdeveloper.in/documentation/api/ 8 | * Symbol Search: https://web.stocksdeveloper.in/instrument 9 | * 10 | * Author - Stocks Developer 11 | */ 12 | 13 | #include 14 | #include 15 | 16 | // Following code adds buttons to the screen 17 | Column_Begin( "1" ); 18 | BuyCommand = TriggerCell( "BUY", colorBrightGreen, colorAqua, colorBlack); 19 | Column_End( ); 20 | 21 | Column_Begin( "2" ); 22 | SellCommand = TriggerCell( "SELL", colorRed, colorLightOrange, colorBlack); 23 | Column_End( ); 24 | 25 | Column_Begin( "3" ); 26 | SellCommand = TriggerCell( "Square Off", colorYellow, colorGold, colorBlack); 27 | Column_End( ); 28 | 29 | // Get co-ordinates 30 | ClickCoordinates = Nz(StaticVarGet("ClickCoordinates")); 31 | 32 | // Take action based on the button placed by user 33 | switch( ClickCoordinates ) 34 | { 35 | case 101: 36 | // Place buy orders when user clicks on BUY button 37 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 38 | message = "Placing BUY order for account [" + (iter + 1) + "] : " + acc; 39 | logDebug(message); 40 | _TRACE(message); 41 | 42 | // You can write any of AutoTrader Web API functions here 43 | placeOrder(acc, AT_EXCHANGE, AT_SYMBOL, "BUY", "MARKET", 44 | AT_PRODUCT_TYPE, AT_QUANTITY, 0, defaultTriggerPrice(), False); 45 | } 46 | break; 47 | 48 | case 201: 49 | // Place sell orders when user clicks on SELL button 50 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 51 | message = "Placing SELL order for account [" + (iter + 1) + "] : " + acc; 52 | logDebug(message); 53 | _TRACE(message); 54 | 55 | // You can write any of AutoTrader Web API functions here 56 | placeOrder(acc, AT_EXCHANGE, AT_SYMBOL, "SELL", "MARKET", 57 | AT_PRODUCT_TYPE, AT_QUANTITY, 0, defaultTriggerPrice(), False); 58 | } 59 | break; 60 | 61 | case 301: 62 | // Place a square off request when user clicks on Square Off button 63 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 64 | message = "Sending square-off position request sent for account [" + (iter + 1) + "] : " + acc 65 | + ", Position : " + AT_SYMBOL; 66 | logDebug(message); 67 | _TRACE(message); 68 | 69 | // You can write any of AutoTrader Web API functions here 70 | positionType = calcPositionType(AT_VARIETY_REGULAR, AT_PRODUCT_TYPE); 71 | squareOffPosition(acc, "NET", positionType, AT_EXCHANGE, AT_SYMBOL); 72 | } 73 | break; 74 | 75 | } -------------------------------------------------------------------------------- /Formulas/AutoTraderWeb/General/MultiAccount/at-ema-crossover-multi-account.afl: -------------------------------------------------------------------------------- 1 | /** 2 | * AmiBroker moving average crossover with square-off option (for multiple accounts). 3 | * You need to set appropriate values in chart parameters. 4 | * 5 | * User Guide: https://stocksdeveloper.in/documentation/index/ 6 | * API Docs: https://stocksdeveloper.in/documentation/api/ 7 | * Symbol Search: https://stocksdeveloper.in:9013/instrument 8 | * 9 | * Author - Stocks Developer 10 | */ 11 | 12 | /******************************************************************** 13 | * SECTION 1 - BEGIN 14 | * This section contains all includes & should be at the top of your strategy afl. 15 | ********************************************************************/ 16 | 17 | #include 18 | #include 19 | #include 20 | 21 | /******************************************************************** 22 | * SECTION 1 - END 23 | ********************************************************************/ 24 | 25 | 26 | /******************************************************************* 27 | * Moving average crossover with auto square off. 28 | * This strategy works well with market orders. 29 | * This strategy also shows how can we avoid Short & Cover by doubling 30 | * quantity on all orders except the first one. 31 | * 32 | * There are many configurations available, please see chart parameters: 33 | * - Automated time based square-off 34 | * - Ability to place order on next bar or candle 35 | * 36 | * NOTE: It is recommended to start with a blank chart. 37 | ********************************************************************/ 38 | 39 | /******************************************************************* 40 | * How to see strategy logs in AMIBroker? 41 | * 1. Enable log window from amibroker menu (Window -> Log) 42 | * 2. You will see log window at the bottom. 43 | * 3. Go to "Trace" tab (all strategy logs are printed here). 44 | ********************************************************************/ 45 | 46 | 47 | /******************************************************************** 48 | * SECTION 2 - BEGIN 49 | * This section contains your strategy afl code. 50 | ********************************************************************/ 51 | 52 | _SECTION_BEGIN("Moving Average - Multiple Accounts"); 53 | 54 | // Account names parameter 55 | AT_ACCOUNTS = ParamStr("Accounts (comma separated)", "ACC1,ACC2,ACC3"); 56 | 57 | // Moving Average 58 | SHORT_MA_PERIOD = Param("Short term moving average period", 20, 1, 200, 2); 59 | LONG_MA_PERIOD = Param("Long term moving average period", 40, 1, 200, 2); 60 | 61 | // Refresh even when minimized, see below link 62 | // https://forum.amibroker.com/t/program-pauses-when-amibroker-minimized/4145/2 63 | RefreshPeriod = Param( "Timed Refresh Period", 5, 1, 300); 64 | RequestTimedRefresh(RefreshPeriod, False); 65 | 66 | /* Exponential Moving averages */ 67 | EMA1 = EMA( C, SHORT_MA_PERIOD); 68 | EMA2 = EMA( C, LONG_MA_PERIOD); 69 | 70 | /* Buy and Sell Condition */ 71 | Buy = Cross(EMA1,EMA2); 72 | Sell = Cross(EMA2,EMA1); 73 | 74 | /* Remove excess signals */ 75 | Buy = ExRem(Buy,Sell); 76 | Sell = ExRem(Sell,Buy); 77 | 78 | // This is only added for backtesting 79 | Short=Sell; 80 | Cover=Buy; 81 | 82 | /* Prices when Buy, Sell, Short, Cover condition is true */ 83 | //buyPrice = ValueWhen(Buy,C); 84 | //sellPrice = ValueWhen(Sell,C); 85 | 86 | /* We use live prices here, as ValueWhen function gives negative price sometimes */ 87 | buyPrice = LastValue(C); 88 | sellPrice = LastValue(C); 89 | 90 | /* Plot Buy and Sell Signal Arrows */ 91 | shape = Buy * shapeUpArrow + Sell * shapeDownArrow; 92 | PlotShapes( shape, IIf( Buy, colorGreen, colorRed ), 0, IIf( Buy, Low, High ) ); 93 | GraphXSpace = 5; 94 | 95 | /* Plot EMA lines and Candles */ 96 | Plot(EMA1,"EMA", colorRed); 97 | Plot(EMA2,"EMA2", colorGreen); 98 | Plot(C, "Close", colorRed, styleCandle); 99 | 100 | 101 | /******************************************************************** 102 | * SECTION 2 - END 103 | ********************************************************************/ 104 | 105 | 106 | /******************************************************************** 107 | * SECTION 3 - BEGIN 108 | * This section contains your code for placing orders. 109 | ********************************************************************/ 110 | 111 | /* 112 | * shouldSquareOff() returns True, when current time goes beyond square off time. 113 | */ 114 | if(shouldSquareOff()) { 115 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 116 | if(!isSquareOffRequestSentForAcc(acc)) { 117 | message = "Sending square-off position request for account [" + (iter + 1) + "] : " + acc; 118 | logDebug(message); 119 | _TRACE(message); 120 | 121 | // Square off position, as current time has gone passed square off time 122 | // Assuming the position is MIS 123 | squareOffPosition(acc, "DAY", "MIS", AT_EXCHANGE, AT_SYMBOL); 124 | 125 | saveStaticVariable(acc, AT_SQUARE_OFF_STATUS_KEY, 1); 126 | } 127 | } 128 | } 129 | else { 130 | 131 | BuySignal = Buy; 132 | SellSignal = Sell; 133 | 134 | if(AT_PLACE_ORDER_ON_NEXT_BAR) { 135 | // Use signals from previous bar (when place order on next bar is turned on) 136 | BuySignal = Ref(Buy, -1); 137 | SellSignal = Ref(Sell, -1); 138 | } 139 | 140 | /* 141 | * If control reaches here, it means we are before square off time, 142 | * so we can place orders. 143 | */ 144 | if ( LastValue(BuySignal) == True && isNewBar() ) 145 | { 146 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 147 | message = "Placing BUY order for account [" + (iter + 1) + "] : " + acc; 148 | logDebug(message); 149 | _TRACE(message); 150 | 151 | /* 152 | * We do some calculation to double the quantity, for all orders except first. 153 | * This is done so that we can re-enter a position. Following this approach 154 | * we can avoid using Short & Cover. 155 | */ 156 | quantity = calcDoubleQuantity(acc, AT_SYMBOL, AT_QUANTITY); 157 | 158 | placeOrder(acc, AT_EXCHANGE, AT_SYMBOL, "BUY", "MARKET", 159 | AT_PRODUCT_TYPE, quantity, buyPrice, defaultTriggerPrice(), True); 160 | } 161 | } 162 | 163 | if ( LastValue(SellSignal) == True && isNewBar() ) 164 | { 165 | 166 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 167 | message = "Placing SELL order for account [" + (iter + 1) + "] : " + acc; 168 | logDebug(message); 169 | _TRACE(message); 170 | 171 | /* 172 | * We do some calculation to double the quantity, for all orders except first. 173 | * This is done so that we can re-enter a position. Following this approach 174 | * we can avoid using Short & Cover. 175 | */ 176 | quantity = calcDoubleQuantity(acc, AT_SYMBOL, AT_QUANTITY); 177 | 178 | placeOrder(acc, AT_EXCHANGE, AT_SYMBOL, "SELL", "MARKET", 179 | AT_PRODUCT_TYPE, quantity, sellPrice, defaultTriggerPrice(), True); 180 | } 181 | } 182 | 183 | if(AT_PLACE_ORDER_ON_NEXT_BAR) { 184 | // Special handling when place order on next bar or candle is ON 185 | // This must be done after place order code 186 | 187 | if(LastValue(Buy) == True || LastValue(Sell) == True || 188 | LastValue(Short) == True || LastValue(Cover) == True) { 189 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 190 | // Save time of current bar when we get signal 191 | saveStaticVariable(acc, AT_PREVIOUS_BAR_END_TIME, Status( "lastbarend" )); 192 | } 193 | } 194 | } 195 | 196 | } 197 | 198 | /******************************************************************** 199 | * SECTION 3 - END 200 | ********************************************************************/ 201 | 202 | _SECTION_END(); 203 | -------------------------------------------------------------------------------- /Formulas/AutoTraderWeb/General/MultiAccount/at-supertrend-multi-account.afl: -------------------------------------------------------------------------------- 1 | /** 2 | * AmiBroker supertrend with square-off option (for multiple accounts). 3 | * You need to set appropriate values in chart parameters. 4 | * 5 | * User Guide: https://stocksdeveloper.in/documentation/index/ 6 | * API Docs: https://stocksdeveloper.in/documentation/api/ 7 | * Symbol Search: https://stocksdeveloper.in:9013/instrument 8 | * 9 | * Author - Stocks Developer 10 | */ 11 | 12 | /******************************************************************** 13 | * SECTION 1 - BEGIN 14 | * This section contains all includes & should be at the top of your strategy afl. 15 | ********************************************************************/ 16 | 17 | #include 18 | #include 19 | #include 20 | 21 | /******************************************************************** 22 | * SECTION 1 - END 23 | ********************************************************************/ 24 | 25 | /******************************************************************* 26 | * SuperTrend indicator based automated trading afl example. 27 | * 28 | * There are many configurations available, please see chart parameters: 29 | * - Automated time based square-off 30 | * - Ability to place order on next bar or candle 31 | * 32 | * NOTE: It is recommended to start with a blank chart. 33 | ********************************************************************/ 34 | 35 | /******************************************************************* 36 | * How to see strategy logs in AMIBroker? 37 | * 1. Enable log window from amibroker menu (Window -> Log) 38 | * 2. You will see log window at the bottom. 39 | * 3. Go to "Trace" tab (all strategy logs are printed here). 40 | ********************************************************************/ 41 | 42 | 43 | /******************************************************************** 44 | * SECTION 2 - BEGIN 45 | * This section contains your strategy afl code. 46 | ********************************************************************/ 47 | 48 | _SECTION_BEGIN("Supertrend - Multiple Accounts"); 49 | 50 | // Account names parameter 51 | AT_ACCOUNTS = ParamStr("Accounts (comma separated)", "ACC1,ACC2,ACC3"); 52 | 53 | // SuperTrend parameters 54 | Multiplier = Param("Period", 7, 1, 50 ); 55 | Period = Param("Multiplier", 3, 1, 10 ); 56 | 57 | // Chart parameters 58 | UpColor = ParamColor("Up Color", colorGreen); 59 | DownColor = ParamColor("Down Color", colorRed); 60 | WickUpColor = ParamColor("Wick UP Color", colorLime); 61 | WickDownColor = ParamColor("Wick Down Color", colorOrange); 62 | ResistanceColor = ParamColor("Resistance", colorRed); 63 | SupportColor = ParamColor( "Support", colorGreen); 64 | Style = ParamStyle("Line Style", styleThick); 65 | 66 | // Refresh even when minimized, see below link 67 | // https://forum.amibroker.com/t/program-pauses-when-amibroker-minimized/4145/2 68 | RefreshPeriod = Param( "Timed Refresh Period", 5, 1, 300); 69 | RequestTimedRefresh(RefreshPeriod, False); 70 | 71 | SetChartOptions(0, chartShowArrows|chartShowDates); 72 | 73 | SetBarFillColor(IIf(C>O, UpColor, IIf(C<=O, DownColor, colorLightGrey))); 74 | 75 | Plot(C, "Price", IIf(C>O, WickUpColor, IIf(C<=O, WickDownColor, colorLightGrey)), styleCandle | styleNoTitle); 76 | 77 | _N(Title = "Supertrend: " + 78 | StrFormat("{{INTERVAL}} {{DATE}} \nOpen= %g, HiGH= %g, LoW= %g, Close= %g (%.1f%%) {{VALUES}}", 79 | O, H, L, C, SelectedValue( ROC( C, 1 ) ) )); 80 | 81 | function calculateSupertrend(Period, Multiplier) 82 | { 83 | ATR_Val=ATR(Period); 84 | 85 | UpperBand=LowerBand=final_UpperBand=final_LowerBand=SuperTrend=0; 86 | 87 | for( i = Period; i < BarCount; i++ ) 88 | { 89 | UpperBand[i]=((High[i] + Low[i])/2) + Multiplier*ATR_Val[i]; 90 | LowerBand[i]=((High[i] + Low[i])/2) - Multiplier*ATR_Val[i]; 91 | final_UpperBand[i] = IIf( ((UpperBand[i]final_UpperBand[i-1])), (UpperBand[i]), final_UpperBand[i-1]); 92 | final_LowerBand[i] = Iif( ((LowerBand[i]>final_LowerBand[i-1]) OR (Close[i-1]=final_UpperBand[i])),final_LowerBand[i], 96 | IIf(((SuperTrend[i-1]==final_LowerBand[i-1]) AND (Close[i]>=final_LowerBand[i])),final_LowerBand[i], 97 | IIf(((SuperTrend[i-1]==final_LowerBand[i-1]) AND (Close[i]<=final_LowerBand[i])),final_UpperBand[i],0)))); 98 | 99 | } 100 | 101 | Plot( SuperTrend, "SuperTrend", IIf( SuperTrend>Close, ResistanceColor, SupportColor), Style); 102 | Return SuperTrend; 103 | } 104 | 105 | SuperTrend = calculateSupertrend(Period,Multiplier); 106 | 107 | // This will tell us if the line is green or red (i.e. buy or sell) 108 | // Close > Supertrend == BUY Signal otherwise SELL 109 | SupertrendSignal = Close > SuperTrend; 110 | 111 | // This will tell us whenever there is a change in signal 112 | SignalChanged = SupertrendSignal != Ref(SupertrendSignal, -1); 113 | 114 | // If supertrend is buy and signal just changed 115 | Buy = SupertrendSignal AND SignalChanged; 116 | 117 | // If supertrend is sell and signal just changed 118 | Sell = (!SupertrendSignal) AND SignalChanged; 119 | 120 | // Additional safety, remove excessive signals 121 | Buy=ExRem(Buy,Sell); 122 | Sell=ExRem(Sell,Buy); 123 | 124 | // This is only added for backtesting 125 | Short=Sell; 126 | Cover=Buy; 127 | 128 | /******************************************************************** 129 | * SECTION 2 - END 130 | ********************************************************************/ 131 | 132 | /******************************************************************** 133 | * SECTION 3 - BEGIN 134 | * This section contains your code for placing orders. 135 | ********************************************************************/ 136 | /* 137 | * shouldSquareOff() returns 1 when current time goes beyond square off time. 138 | */ 139 | if(shouldSquareOff()) { 140 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 141 | if(!isSquareOffRequestSentForAcc(acc)) { 142 | message = "Sending square-off position request for account [" + (iter + 1) + "] : " + acc; 143 | logDebug(message); 144 | _TRACE(message); 145 | 146 | // Square off position, as current time has gone passed square off time 147 | // Assuming the position is MIS 148 | squareOffPosition(acc, "DAY", "MIS", AT_EXCHANGE, AT_SYMBOL); 149 | 150 | saveStaticVariable(acc, AT_SQUARE_OFF_STATUS_KEY, 1); 151 | } 152 | } 153 | } 154 | else { 155 | 156 | BuySignal = Buy; 157 | SellSignal = Sell; 158 | 159 | if(AT_PLACE_ORDER_ON_NEXT_BAR) { 160 | // Use signals from previous bar (when place order on next bar is turned on) 161 | BuySignal = Ref(Buy, -1); 162 | SellSignal = Ref(Sell, -1); 163 | } 164 | 165 | /* 166 | * If control reaches here, it means we are before square off time, 167 | * so we can place orders. 168 | */ 169 | if ( LastValue(BuySignal) == True && isNewBar() ) 170 | { 171 | 172 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 173 | message = "Placing BUY order for account [" + (iter + 1) + "] : " + acc; 174 | logDebug(message); 175 | _TRACE(message); 176 | 177 | /* 178 | * We do some calculation to double the quantity, for all orders except first. 179 | * This is done so that we can re-enter a position. Following this approach 180 | * we can avoid using Short & Cover. 181 | */ 182 | quantity = calcDoubleQuantity(acc, AT_SYMBOL, AT_QUANTITY); 183 | 184 | placeOrder(acc, AT_EXCHANGE, AT_SYMBOL, "BUY", "MARKET", 185 | AT_PRODUCT_TYPE, quantity, buyPrice, defaultTriggerPrice(), True); 186 | } 187 | } 188 | 189 | if ( LastValue(SellSignal) == True && isNewBar() ) 190 | { 191 | 192 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 193 | message = "Placing SELL order for account [" + (iter + 1) + "] : " + acc; 194 | logDebug(message); 195 | _TRACE(message); 196 | 197 | /* 198 | * We do some calculation to double the quantity, for all orders except first. 199 | * This is done so that we can re-enter a position. Following this approach 200 | * we can avoid using Short & Cover. 201 | */ 202 | quantity = calcDoubleQuantity(acc, AT_SYMBOL, AT_QUANTITY); 203 | 204 | placeOrder(acc, AT_EXCHANGE, AT_SYMBOL, "SELL", "MARKET", 205 | AT_PRODUCT_TYPE, quantity, sellPrice, defaultTriggerPrice(), True); 206 | } 207 | } 208 | 209 | if(AT_PLACE_ORDER_ON_NEXT_BAR) { 210 | // Special handling when place order on next bar or candle is ON 211 | // This must be done after place order code 212 | 213 | if(LastValue(Buy) == True || LastValue(Sell) == True || 214 | LastValue(Short) == True || LastValue(Cover) == True) { 215 | for(iter = 0; !strIsEmpty(acc = StrExtract(AT_ACCOUNTS, iter)); iter++ ) { 216 | // Save time of current bar when we get signal 217 | saveStaticVariable(acc, AT_PREVIOUS_BAR_END_TIME, Status( "lastbarend" )); 218 | } 219 | } 220 | } 221 | 222 | } 223 | /******************************************************************** 224 | * SECTION 3 - END 225 | ********************************************************************/ 226 | 227 | _SECTION_END(); -------------------------------------------------------------------------------- /Formulas/AutoTraderWeb/General/at-ema-buy-sell-short-cover.afl: -------------------------------------------------------------------------------- 1 | /** 2 | * AmiBroker moving average crossover with square-off option. 3 | * This strategy makes use of Buy, Sell, Short & Cover signals. 4 | * You need to set appropriate values in chart parameters. 5 | * 6 | * User Guide: https://stocksdeveloper.in/documentation/index/ 7 | * API Docs: https://stocksdeveloper.in/documentation/api/ 8 | * Symbol Search: https://stocksdeveloper.in:9013/instrument 9 | * 10 | * Author - Stocks Developer 11 | */ 12 | 13 | /******************************************************************** 14 | * SECTION 1 - BEGIN 15 | * This section contains all includes & should be at the top of your strategy afl. 16 | ********************************************************************/ 17 | 18 | #include 19 | #include 20 | #include 21 | 22 | /******************************************************************** 23 | * SECTION 1 - END 24 | ********************************************************************/ 25 | 26 | 27 | /******************************************************************* 28 | * Moving average crossover with auto square off. 29 | * This strategy works well with market orders. 30 | * This strategy makes use of Buy, Sell, Short & Cover signals. 31 | * 32 | * There are many configurations available, please see chart parameters: 33 | * - Automated time based square-off 34 | * - Ability to place order on next bar or candle 35 | * 36 | * NOTE: It is recommended to start with a blank chart. 37 | ********************************************************************/ 38 | 39 | /******************************************************************* 40 | * How to see strategy logs in AMIBroker? 41 | * 1. Enable log window from amibroker menu (Window -> Log) 42 | * 2. You will see log window at the bottom. 43 | * 3. Go to "Trace" tab (all strategy logs are printed here). 44 | ********************************************************************/ 45 | 46 | 47 | /******************************************************************** 48 | * SECTION 2 - BEGIN 49 | * This section contains your strategy afl code. 50 | ********************************************************************/ 51 | 52 | _SECTION_BEGIN("Moving Average: Buy-Sell-Short-Cover"); 53 | 54 | // Moving Average 55 | SHORT_MA_PERIOD = Param("Short term moving average period", 20, 1, 200, 2); 56 | LONG_MA_PERIOD = Param("Long term moving average period", 40, 1, 200, 2); 57 | 58 | // Refresh even when minimized, see below link 59 | // https://forum.amibroker.com/t/program-pauses-when-amibroker-minimized/4145/2 60 | RefreshPeriod = Param( "Timed Refresh Period", 5, 1, 300); 61 | RequestTimedRefresh(RefreshPeriod, False); 62 | 63 | ORDER_COUNT = "ORDER_COUNT"; 64 | LAST_SIGNAL = "LAST_SIGNAL"; 65 | 66 | function getPlacedOrderCount() { 67 | return Nz(readStaticVariable(AT_ACCOUNT, ORDER_COUNT)); 68 | } 69 | 70 | function incrementPlacedOrderCount(lastOrderId) { 71 | if(lastOrderId != "") { 72 | saveStaticVariable(AT_ACCOUNT, ORDER_COUNT, getPlacedOrderCount() + 1); 73 | } 74 | } 75 | 76 | function getPreviousSignal() { 77 | return readStaticVariableText(AT_ACCOUNT, LAST_SIGNAL); 78 | } 79 | 80 | function setPreviousSignal(signalType) { 81 | return saveStaticVariableText(AT_ACCOUNT, LAST_SIGNAL, signalType); 82 | } 83 | 84 | /* Exponential Moving averages */ 85 | EMA1 = EMA( C, SHORT_MA_PERIOD); 86 | EMA2 = EMA( C, LONG_MA_PERIOD); 87 | 88 | /* Buy and Sell Condition */ 89 | Buy = Cross(EMA1,EMA2); 90 | Sell = Cross(EMA2,EMA1); 91 | 92 | /* Remove excess signals */ 93 | Buy = ExRem(Buy,Sell); 94 | Sell = ExRem(Sell,Buy); 95 | 96 | /* You can add your own conditions for Short & Cover */ 97 | Short = Sell; 98 | Cover = Buy; 99 | 100 | /* Prices when Buy, Sell, Short, Cover condition is true */ 101 | //buyPrice = ValueWhen(Buy,C); 102 | //sellPrice = ValueWhen(Sell,C); 103 | 104 | /* We use live prices here, as ValueWhen function gives negative price sometimes */ 105 | /* You can use a different price as well */ 106 | buyPrice = LastValue(C); 107 | sellPrice = LastValue(C); 108 | shortPrice = LastValue(C); 109 | coverPrice = LastValue(C); 110 | 111 | /* Plot Buy and Sell Signal Arrows */ 112 | shape = Buy * shapeUpArrow + Sell * shapeDownArrow; 113 | PlotShapes( shape, IIf( Buy, colorGreen, colorRed ), 0, IIf( Buy, Low, High ) ); 114 | GraphXSpace = 5; 115 | 116 | /* Plot EMA lines and Candles */ 117 | Plot(EMA1,"EMA", colorRed); 118 | Plot(EMA2,"EMA2", colorGreen); 119 | Plot(C, "Close", colorRed, styleCandle); 120 | 121 | 122 | /******************************************************************** 123 | * SECTION 2 - END 124 | ********************************************************************/ 125 | 126 | 127 | /******************************************************************** 128 | * SECTION 3 - BEGIN 129 | * This section contains your code for placing orders. 130 | ********************************************************************/ 131 | 132 | /* 133 | * shouldSquareOff() returns True, when current time goes beyond square off time. 134 | */ 135 | if(shouldSquareOff()) { 136 | if(!isSquareOffRequestSent()) { 137 | // Square off position, as current time has gone passed square off time 138 | // Assuming the position is MIS 139 | squareOffPosition(AT_ACCOUNT, "DAY", "MIS", AT_EXCHANGE, AT_SYMBOL); 140 | 141 | saveStaticVariable(AT_ACCOUNT, AT_SQUARE_OFF_STATUS_KEY, 1); 142 | } 143 | } 144 | else { 145 | 146 | orderCount = getPlacedOrderCount(); 147 | 148 | BuySignal = Buy; 149 | SellSignal = Sell; 150 | ShortSignal = Short; 151 | CoverSignal = Cover; 152 | 153 | if(AT_PLACE_ORDER_ON_NEXT_BAR) { 154 | // Use signals from previous bar (when place order on next bar is turned on) 155 | BuySignal = Ref(Buy, -1); 156 | SellSignal = Ref(Sell, -1); 157 | ShortSignal = Ref(Short, -1); 158 | CoverSignal = Ref(Cover, -1); 159 | } 160 | 161 | /* 162 | * If control reaches here, it means we are before square off time, 163 | * so we can place orders. 164 | */ 165 | if ( LastValue(BuySignal) == True && getPreviousSignal() != "COVER" && isNewBar() ) 166 | { 167 | orderId = placeOrder(AT_ACCOUNT, AT_EXCHANGE, AT_SYMBOL, "BUY", "MARKET", 168 | AT_PRODUCT_TYPE, AT_QUANTITY, buyPrice, defaultTriggerPrice(), True); 169 | incrementPlacedOrderCount(orderId); 170 | setPreviousSignal("BUY"); 171 | } 172 | 173 | if ( LastValue(SellSignal) == True && orderCount > 1 && 174 | getPreviousSignal() != "SHORT" && isNewBar() ) 175 | { 176 | orderId = placeOrder(AT_ACCOUNT, AT_EXCHANGE, AT_SYMBOL, "SELL", "MARKET", 177 | AT_PRODUCT_TYPE, AT_QUANTITY, sellPrice, defaultTriggerPrice(), True); 178 | incrementPlacedOrderCount(orderId); 179 | setPreviousSignal("SELL"); 180 | } 181 | 182 | if ( LastValue(ShortSignal) == True && isNewBar() ) 183 | { 184 | orderId = placeOrder(AT_ACCOUNT, AT_EXCHANGE, AT_SYMBOL, "SHORT", "MARKET", 185 | AT_PRODUCT_TYPE, AT_QUANTITY, buyPrice, defaultTriggerPrice(), True); 186 | incrementPlacedOrderCount(orderId); 187 | setPreviousSignal("SHORT"); 188 | } 189 | 190 | if ( LastValue(CoverSignal) == True && orderCount > 1 && isNewBar() ) 191 | { 192 | orderId = placeOrder(AT_ACCOUNT, AT_EXCHANGE, AT_SYMBOL, "COVER", "MARKET", 193 | AT_PRODUCT_TYPE, AT_QUANTITY, sellPrice, defaultTriggerPrice(), True); 194 | incrementPlacedOrderCount(orderId); 195 | setPreviousSignal("COVER"); 196 | } 197 | 198 | if(AT_PLACE_ORDER_ON_NEXT_BAR) { 199 | // Special handling when place order on next bar or candle is ON 200 | // This must be done after place order code 201 | 202 | if(LastValue(Buy) == True || LastValue(Sell) == True || 203 | LastValue(Short) == True || LastValue(Cover) == True) { 204 | // Save time of current bar when we get signal 205 | saveStaticVariable(AT_ACCOUNT, AT_PREVIOUS_BAR_END_TIME, Status( "lastbarend" )); 206 | } 207 | } 208 | 209 | } 210 | 211 | /******************************************************************** 212 | * SECTION 3 - END 213 | ********************************************************************/ 214 | 215 | _SECTION_END(); 216 | -------------------------------------------------------------------------------- /Formulas/AutoTraderWeb/General/at-ema-crossover.afl: -------------------------------------------------------------------------------- 1 | /** 2 | * AmiBroker moving average crossover with square-off option. 3 | * You need to set appropriate values in chart parameters. 4 | * 5 | * User Guide: https://stocksdeveloper.in/documentation/index/ 6 | * API Docs: https://stocksdeveloper.in/documentation/api/ 7 | * Symbol Search: https://stocksdeveloper.in:9013/instrument 8 | * 9 | * Author - Stocks Developer 10 | */ 11 | 12 | /******************************************************************** 13 | * SECTION 1 - BEGIN 14 | * This section contains all includes & should be at the top of your strategy afl. 15 | ********************************************************************/ 16 | 17 | #include 18 | #include 19 | #include 20 | 21 | /******************************************************************** 22 | * SECTION 1 - END 23 | ********************************************************************/ 24 | 25 | 26 | /******************************************************************* 27 | * Moving average crossover with auto square off. 28 | * This strategy works well with market orders. 29 | * This strategy also shows how can we avoid Short & Cover by doubling 30 | * quantity on all orders except the first one. 31 | * 32 | * There are many configurations available, please see chart parameters: 33 | * - Automated time based square-off 34 | * - Ability to place order on next bar or candle 35 | * 36 | * NOTE: It is recommended to start with a blank chart. 37 | ********************************************************************/ 38 | 39 | /******************************************************************* 40 | * How to see strategy logs in AMIBroker? 41 | * 1. Enable log window from amibroker menu (Window -> Log) 42 | * 2. You will see log window at the bottom. 43 | * 3. Go to "Trace" tab (all strategy logs are printed here). 44 | ********************************************************************/ 45 | 46 | 47 | /******************************************************************** 48 | * SECTION 2 - BEGIN 49 | * This section contains your strategy afl code. 50 | ********************************************************************/ 51 | 52 | _SECTION_BEGIN("Moving Average"); 53 | 54 | // Moving Average 55 | SHORT_MA_PERIOD = Param("Short term moving average period", 20, 1, 200, 2); 56 | LONG_MA_PERIOD = Param("Long term moving average period", 40, 1, 200, 2); 57 | 58 | // Refresh even when minimized, see below link 59 | // https://forum.amibroker.com/t/program-pauses-when-amibroker-minimized/4145/2 60 | RefreshPeriod = Param( "Timed Refresh Period", 5, 1, 300); 61 | RequestTimedRefresh(RefreshPeriod, False); 62 | 63 | /* Exponential Moving averages */ 64 | EMA1 = EMA( C, SHORT_MA_PERIOD); 65 | EMA2 = EMA( C, LONG_MA_PERIOD); 66 | 67 | /* Buy and Sell Condition */ 68 | Buy = Cross(EMA1,EMA2); 69 | Sell = Cross(EMA2,EMA1); 70 | 71 | /* Remove excess signals */ 72 | Buy = ExRem(Buy,Sell); 73 | Sell = ExRem(Sell,Buy); 74 | 75 | // This is only added for backtesting 76 | Short=Sell; 77 | Cover=Buy; 78 | 79 | /* Prices when Buy, Sell, Short, Cover condition is true */ 80 | //buyPrice = ValueWhen(Buy,C); 81 | //sellPrice = ValueWhen(Sell,C); 82 | 83 | /* We use live prices here, as ValueWhen function gives negative price sometimes */ 84 | buyPrice = LastValue(C); 85 | sellPrice = LastValue(C); 86 | 87 | /* Plot Buy and Sell Signal Arrows */ 88 | shape = Buy * shapeUpArrow + Sell * shapeDownArrow; 89 | PlotShapes( shape, IIf( Buy, colorGreen, colorRed ), 0, IIf( Buy, Low, High ) ); 90 | GraphXSpace = 5; 91 | 92 | /* Plot EMA lines and Candles */ 93 | Plot(EMA1,"EMA", colorRed); 94 | Plot(EMA2,"EMA2", colorGreen); 95 | Plot(C, "Close", colorRed, styleCandle); 96 | 97 | 98 | /******************************************************************** 99 | * SECTION 2 - END 100 | ********************************************************************/ 101 | 102 | 103 | /******************************************************************** 104 | * SECTION 3 - BEGIN 105 | * This section contains your code for placing orders. 106 | ********************************************************************/ 107 | 108 | /* 109 | * shouldSquareOff() returns True, when current time goes beyond square off time. 110 | */ 111 | if(shouldSquareOff()) { 112 | if(!isSquareOffRequestSent()) { 113 | // Square off position, as current time has gone passed square off time 114 | // Assuming the position is MIS 115 | squareOffPosition(AT_ACCOUNT, "DAY", "MIS", AT_EXCHANGE, AT_SYMBOL); 116 | 117 | saveStaticVariable(AT_ACCOUNT, AT_SQUARE_OFF_STATUS_KEY, 1); 118 | } 119 | } 120 | else { 121 | 122 | BuySignal = Buy; 123 | SellSignal = Sell; 124 | 125 | if(AT_PLACE_ORDER_ON_NEXT_BAR) { 126 | // Use signals from previous bar (when place order on next bar is turned on) 127 | BuySignal = Ref(Buy, -1); 128 | SellSignal = Ref(Sell, -1); 129 | } 130 | 131 | /* 132 | * If control reaches here, it means we are before square off time, 133 | * so we can place orders. 134 | */ 135 | if ( LastValue(BuySignal) == True && isNewBar() ) 136 | { 137 | /* 138 | * We do some calculation to double the quantity, for all orders except first. 139 | * This is done so that we can re-enter a position. Following this approach 140 | * we can avoid using Short & Cover. 141 | */ 142 | quantity = calcDoubleQuantity(AT_ACCOUNT, AT_SYMBOL, AT_QUANTITY); 143 | 144 | placeOrder(AT_ACCOUNT, AT_EXCHANGE, AT_SYMBOL, "BUY", "MARKET", 145 | AT_PRODUCT_TYPE, quantity, buyPrice, defaultTriggerPrice(), True); 146 | } 147 | 148 | if ( LastValue(SellSignal) == True && isNewBar() ) 149 | { 150 | quantity = calcDoubleQuantity(AT_ACCOUNT, AT_SYMBOL, AT_QUANTITY); 151 | 152 | placeOrder(AT_ACCOUNT, AT_EXCHANGE, AT_SYMBOL, "SELL", "MARKET", 153 | AT_PRODUCT_TYPE, quantity, sellPrice, defaultTriggerPrice(), True); 154 | } 155 | 156 | if(AT_PLACE_ORDER_ON_NEXT_BAR) { 157 | // Special handling when place order on next bar or candle is ON 158 | // This must be done after place order code 159 | 160 | if(LastValue(Buy) == True || LastValue(Sell) == True || 161 | LastValue(Short) == True || LastValue(Cover) == True) { 162 | // Save time of current bar when we get signal 163 | saveStaticVariable(AT_ACCOUNT, AT_PREVIOUS_BAR_END_TIME, Status( "lastbarend" )); 164 | } 165 | } 166 | 167 | } 168 | 169 | /******************************************************************** 170 | * SECTION 3 - END 171 | ********************************************************************/ 172 | 173 | _SECTION_END(); 174 | -------------------------------------------------------------------------------- /Formulas/AutoTraderWeb/General/at-supertrend-scanner.afl: -------------------------------------------------------------------------------- 1 | /** 2 | * AmiBroker supertrend with square-off option. 3 | * This afl shows the changes you need to run a AFL in scanner. 4 | * There is also a provision to use a symbol mapping file & quantity file. 5 | * You need to set appropriate values in scanner parameters. 6 | ******************************************************************* 7 | * The symbol mapping file should contain comma separated values. 8 | * Format: Datafeed Symbol,AutoTrader Web Symbol 9 | * Example: 10 | * BANKNIFTY-I,BANKNIFTY_24-SEP-2020_FUT 11 | * BANKNIFTY-II,BANKNIFTY_26-NOV-2020_FUT 12 | * NIFTY-I,NIFTY_24-SEP-2020_FUT 13 | ******************************************************************** 14 | * The quantity mapping file should contain comma separated values. 15 | * Format: Datafeed Symbol,Quantity 16 | * Example: 17 | * BANKNIFTY-I,50 18 | * BANKNIFTY-II,25 19 | * NIFTY-I,75 20 | ******************************************************************* 21 | * User Guide: https://stocksdeveloper.in/documentation/index/ 22 | * API Docs: https://stocksdeveloper.in/documentation/api/ 23 | * Symbol Search: https://stocksdeveloper.in:9013/instrument 24 | * 25 | * Author - Stocks Developer 26 | */ 27 | 28 | /******************************************************************** 29 | * SECTION 1 - BEGIN 30 | * This section contains all includes & should be at the top of your strategy afl. 31 | ********************************************************************/ 32 | 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | 39 | /******************************************************************** 40 | * SECTION 1 - END 41 | ********************************************************************/ 42 | 43 | /******************************************************************* 44 | * SuperTrend indicator based automated trading afl example. 45 | * 46 | * There are many configurations available, please see chart parameters: 47 | * - Automated time based square-off 48 | * - Ability to place order on next bar or candle 49 | * - Ability to map datafeed symbol to API symbol 50 | * - Ability to use different quantity per symbol 51 | * 52 | * NOTE: It is recommended to start with a blank chart. 53 | ********************************************************************/ 54 | 55 | /******************************************************************* 56 | * How to see strategy logs in AMIBroker? 57 | * 1. Enable log window from amibroker menu (Window -> Log) 58 | * 2. You will see log window at the bottom. 59 | * 3. Go to "Trace" tab (all strategy logs are printed here). 60 | ********************************************************************/ 61 | 62 | 63 | /******************************************************************** 64 | * SECTION 2 - BEGIN 65 | * This section contains your strategy afl code. 66 | ********************************************************************/ 67 | 68 | _SECTION_BEGIN("Supertrend"); 69 | 70 | // SuperTrend parameters 71 | Multiplier = Param("Period", 7, 1, 50 ); 72 | Period = Param("Multiplier", 3, 1, 10 ); 73 | 74 | // Chart parameters 75 | UpColor = ParamColor("Up Color", colorGreen); 76 | DownColor = ParamColor("Down Color", colorRed); 77 | WickUpColor = ParamColor("Wick UP Color", colorLime); 78 | WickDownColor = ParamColor("Wick Down Color", colorOrange); 79 | ResistanceColor = ParamColor("Resistance", colorRed); 80 | SupportColor = ParamColor( "Support", colorGreen); 81 | Style = ParamStyle("Line Style", styleThick); 82 | 83 | // Refresh even when minimized, see below link 84 | // https://forum.amibroker.com/t/program-pauses-when-amibroker-minimized/4145/2 85 | RefreshPeriod = Param( "Timed Refresh Period", 5, 1, 300); 86 | RequestTimedRefresh(RefreshPeriod, False); 87 | 88 | SetChartOptions(0, chartShowArrows|chartShowDates); 89 | 90 | SetBarFillColor(IIf(C>O, UpColor, IIf(C<=O, DownColor, colorLightGrey))); 91 | 92 | Plot(C, "Price", IIf(C>O, WickUpColor, IIf(C<=O, WickDownColor, colorLightGrey)), styleCandle | styleNoTitle); 93 | 94 | _N(Title = "Supertrend: " + 95 | StrFormat("{{INTERVAL}} {{DATE}} \nOpen= %g, HiGH= %g, LoW= %g, Close= %g (%.1f%%) {{VALUES}}", 96 | O, H, L, C, SelectedValue( ROC( C, 1 ) ) )); 97 | 98 | function calculateSupertrend(Period, Multiplier) 99 | { 100 | ATR_Val=ATR(Period); 101 | 102 | UpperBand=LowerBand=final_UpperBand=final_LowerBand=SuperTrend=0; 103 | 104 | for( i = Period; i < BarCount; i++ ) 105 | { 106 | UpperBand[i]=((High[i] + Low[i])/2) + Multiplier*ATR_Val[i]; 107 | LowerBand[i]=((High[i] + Low[i])/2) - Multiplier*ATR_Val[i]; 108 | final_UpperBand[i] = IIf( ((UpperBand[i]final_UpperBand[i-1])), (UpperBand[i]), final_UpperBand[i-1]); 109 | final_LowerBand[i] = Iif( ((LowerBand[i]>final_LowerBand[i-1]) OR (Close[i-1]=final_UpperBand[i])),final_LowerBand[i], 113 | IIf(((SuperTrend[i-1]==final_LowerBand[i-1]) AND (Close[i]>=final_LowerBand[i])),final_LowerBand[i], 114 | IIf(((SuperTrend[i-1]==final_LowerBand[i-1]) AND (Close[i]<=final_LowerBand[i])),final_UpperBand[i],0)))); 115 | 116 | } 117 | 118 | Plot( SuperTrend, "SuperTrend", IIf( SuperTrend>Close, ResistanceColor, SupportColor), Style); 119 | Return SuperTrend; 120 | } 121 | 122 | SuperTrend = calculateSupertrend(Period,Multiplier); 123 | 124 | // This will tell us if the line is green or red (i.e. buy or sell) 125 | // Close > Supertrend == BUY Signal otherwise SELL 126 | SupertrendSignal = Close > SuperTrend; 127 | 128 | // This will tell us whenever there is a change in signal 129 | SignalChanged = SupertrendSignal != Ref(SupertrendSignal, -1); 130 | 131 | // If supertrend is buy and signal just changed 132 | Buy = SupertrendSignal AND SignalChanged; 133 | 134 | // If supertrend is sell and signal just changed 135 | Sell = (!SupertrendSignal) AND SignalChanged; 136 | 137 | // Additional safety, remove excessive signals 138 | Buy=ExRem(Buy,Sell); 139 | Sell=ExRem(Sell,Buy); 140 | 141 | // This is only added for backtesting 142 | Short=Sell; 143 | Cover=Buy; 144 | 145 | /******************************************************************** 146 | * SECTION 2 - END 147 | ********************************************************************/ 148 | 149 | /******************************************************************** 150 | * SECTION 3 - BEGIN 151 | * This section contains your code for placing orders. 152 | ********************************************************************/ 153 | /* 154 | * shouldSquareOff() returns 1 when current time goes beyond square off time. 155 | */ 156 | if(shouldSquareOff()) { 157 | if(!isSquareOffRequestSent()) { 158 | // Square off position, as current time has gone passed square off time 159 | // Assuming the position is MIS 160 | squareOffPosition(AT_ACCOUNT, "DAY", "MIS", AT_EXCHANGE, getSymbol(Name())); 161 | 162 | saveStaticVariable(AT_ACCOUNT, AT_SQUARE_OFF_STATUS_KEY, 1); 163 | } 164 | } 165 | else { 166 | 167 | BuySignal = Buy; 168 | SellSignal = Sell; 169 | 170 | if(AT_PLACE_ORDER_ON_NEXT_BAR) { 171 | // Use signals from previous bar (when place order on next bar is turned on) 172 | BuySignal = Ref(Buy, -1); 173 | SellSignal = Ref(Sell, -1); 174 | } 175 | 176 | /* 177 | * If control reaches here, it means we are before square off time, 178 | * so we can place orders. 179 | */ 180 | if ( LastValue(BuySignal) == True && isNewBar() ) 181 | { 182 | /* 183 | * We do some calculation to double the quantity, for all orders except first. 184 | * This is done so that we can re-enter a position. Following this approach 185 | * we can avoid using Short & Cover. 186 | */ 187 | quantity = calcDoubleQuantity(AT_ACCOUNT, getSymbol(Name()), getQuantity(Name())); 188 | 189 | placeOrder(AT_ACCOUNT, AT_EXCHANGE, getSymbol(Name()), "BUY", "MARKET", 190 | AT_PRODUCT_TYPE, quantity, buyPrice, defaultTriggerPrice(), True); 191 | } 192 | 193 | if ( LastValue(SellSignal) == True && isNewBar() ) 194 | { 195 | /* 196 | * We do some calculation to double the quantity, for all orders except first. 197 | * This is done so that we can re-enter a position. Following this approach 198 | * we can avoid using Short & Cover. 199 | */ 200 | quantity = calcDoubleQuantity(AT_ACCOUNT, getSymbol(Name()), getQuantity(Name())); 201 | 202 | placeOrder(AT_ACCOUNT, AT_EXCHANGE, getSymbol(Name()), "SELL", "MARKET", 203 | AT_PRODUCT_TYPE, quantity, sellPrice, defaultTriggerPrice(), True); 204 | } 205 | 206 | if(AT_PLACE_ORDER_ON_NEXT_BAR) { 207 | // Special handling when place order on next bar or candle is ON 208 | // This must be done after place order code 209 | 210 | if(LastValue(Buy) == True || LastValue(Sell) == True || 211 | LastValue(Short) == True || LastValue(Cover) == True) { 212 | // Save time of current bar when we get signal 213 | saveStaticVariable(AT_ACCOUNT, AT_PREVIOUS_BAR_END_TIME, Status( "lastbarend" )); 214 | } 215 | } 216 | 217 | } 218 | /******************************************************************** 219 | * SECTION 3 - END 220 | ********************************************************************/ 221 | 222 | _SECTION_END(); -------------------------------------------------------------------------------- /Formulas/AutoTraderWeb/General/at-supertrend.afl: -------------------------------------------------------------------------------- 1 | /** 2 | * AmiBroker supertrend with square-off option. 3 | * You need to set appropriate values in chart parameters. 4 | * 5 | * User Guide: https://stocksdeveloper.in/documentation/index/ 6 | * API Docs: https://stocksdeveloper.in/documentation/api/ 7 | * Symbol Search: https://stocksdeveloper.in:9013/instrument 8 | * 9 | * Author - Stocks Developer 10 | */ 11 | 12 | /******************************************************************** 13 | * SECTION 1 - BEGIN 14 | * This section contains all includes & should be at the top of your strategy afl. 15 | ********************************************************************/ 16 | 17 | #include 18 | #include 19 | #include 20 | 21 | /******************************************************************** 22 | * SECTION 1 - END 23 | ********************************************************************/ 24 | 25 | /******************************************************************* 26 | * SuperTrend indicator based automated trading afl example. 27 | * 28 | * There are many configurations available, please see chart parameters: 29 | * - Automated time based square-off 30 | * - Ability to place order on next bar or candle 31 | * 32 | * NOTE: It is recommended to start with a blank chart. 33 | ********************************************************************/ 34 | 35 | /******************************************************************* 36 | * How to see strategy logs in AMIBroker? 37 | * 1. Enable log window from amibroker menu (Window -> Log) 38 | * 2. You will see log window at the bottom. 39 | * 3. Go to "Trace" tab (all strategy logs are printed here). 40 | ********************************************************************/ 41 | 42 | 43 | /******************************************************************** 44 | * SECTION 2 - BEGIN 45 | * This section contains your strategy afl code. 46 | ********************************************************************/ 47 | 48 | _SECTION_BEGIN("Supertrend"); 49 | 50 | // SuperTrend parameters 51 | Multiplier = Param("Period", 7, 1, 50 ); 52 | Period = Param("Multiplier", 3, 1, 10 ); 53 | 54 | // Chart parameters 55 | UpColor = ParamColor("Up Color", colorGreen); 56 | DownColor = ParamColor("Down Color", colorRed); 57 | WickUpColor = ParamColor("Wick UP Color", colorLime); 58 | WickDownColor = ParamColor("Wick Down Color", colorOrange); 59 | ResistanceColor = ParamColor("Resistance", colorRed); 60 | SupportColor = ParamColor( "Support", colorGreen); 61 | Style = ParamStyle("Line Style", styleThick); 62 | 63 | // Refresh even when minimized, see below link 64 | // https://forum.amibroker.com/t/program-pauses-when-amibroker-minimized/4145/2 65 | RefreshPeriod = Param( "Timed Refresh Period", 5, 1, 300); 66 | RequestTimedRefresh(RefreshPeriod, False); 67 | 68 | SetChartOptions(0, chartShowArrows|chartShowDates); 69 | 70 | SetBarFillColor(IIf(C>O, UpColor, IIf(C<=O, DownColor, colorLightGrey))); 71 | 72 | Plot(C, "Price", IIf(C>O, WickUpColor, IIf(C<=O, WickDownColor, colorLightGrey)), styleCandle | styleNoTitle); 73 | 74 | _N(Title = "Supertrend: " + 75 | StrFormat("{{INTERVAL}} {{DATE}} \nOpen= %g, HiGH= %g, LoW= %g, Close= %g (%.1f%%) {{VALUES}}", 76 | O, H, L, C, SelectedValue( ROC( C, 1 ) ) )); 77 | 78 | function calculateSupertrend(Period, Multiplier) 79 | { 80 | ATR_Val=ATR(Period); 81 | 82 | UpperBand=LowerBand=final_UpperBand=final_LowerBand=SuperTrend=0; 83 | 84 | for( i = Period; i < BarCount; i++ ) 85 | { 86 | UpperBand[i]=((High[i] + Low[i])/2) + Multiplier*ATR_Val[i]; 87 | LowerBand[i]=((High[i] + Low[i])/2) - Multiplier*ATR_Val[i]; 88 | final_UpperBand[i] = IIf( ((UpperBand[i]final_UpperBand[i-1])), (UpperBand[i]), final_UpperBand[i-1]); 89 | final_LowerBand[i] = Iif( ((LowerBand[i]>final_LowerBand[i-1]) OR (Close[i-1]=final_UpperBand[i])),final_LowerBand[i], 93 | IIf(((SuperTrend[i-1]==final_LowerBand[i-1]) AND (Close[i]>=final_LowerBand[i])),final_LowerBand[i], 94 | IIf(((SuperTrend[i-1]==final_LowerBand[i-1]) AND (Close[i]<=final_LowerBand[i])),final_UpperBand[i],0)))); 95 | 96 | } 97 | 98 | Plot( SuperTrend, "SuperTrend", IIf( SuperTrend>Close, ResistanceColor, SupportColor), Style); 99 | Return SuperTrend; 100 | } 101 | 102 | SuperTrend = calculateSupertrend(Period,Multiplier); 103 | 104 | // This will tell us if the line is green or red (i.e. buy or sell) 105 | // Close > Supertrend == BUY Signal otherwise SELL 106 | SupertrendSignal = Close > SuperTrend; 107 | 108 | // This will tell us whenever there is a change in signal 109 | SignalChanged = SupertrendSignal != Ref(SupertrendSignal, -1); 110 | 111 | // If supertrend is buy and signal just changed 112 | Buy = SupertrendSignal AND SignalChanged; 113 | 114 | // If supertrend is sell and signal just changed 115 | Sell = (!SupertrendSignal) AND SignalChanged; 116 | 117 | // Additional safety, remove excessive signals 118 | Buy=ExRem(Buy,Sell); 119 | Sell=ExRem(Sell,Buy); 120 | 121 | // This is only added for backtesting 122 | Short=Sell; 123 | Cover=Buy; 124 | 125 | /******************************************************************** 126 | * SECTION 2 - END 127 | ********************************************************************/ 128 | 129 | /******************************************************************** 130 | * SECTION 3 - BEGIN 131 | * This section contains your code for placing orders. 132 | ********************************************************************/ 133 | /* 134 | * shouldSquareOff() returns 1 when current time goes beyond square off time. 135 | */ 136 | if(shouldSquareOff()) { 137 | if(!isSquareOffRequestSent()) { 138 | // Square off position, as current time has gone passed square off time 139 | // Assuming the position is MIS 140 | squareOffPosition(AT_ACCOUNT, "DAY", "MIS", AT_EXCHANGE, AT_SYMBOL); 141 | 142 | saveStaticVariable(AT_ACCOUNT, AT_SQUARE_OFF_STATUS_KEY, 1); 143 | } 144 | } 145 | else { 146 | 147 | BuySignal = Buy; 148 | SellSignal = Sell; 149 | 150 | if(AT_PLACE_ORDER_ON_NEXT_BAR) { 151 | // Use signals from previous bar (when place order on next bar is turned on) 152 | BuySignal = Ref(Buy, -1); 153 | SellSignal = Ref(Sell, -1); 154 | } 155 | 156 | /* 157 | * If control reaches here, it means we are before square off time, 158 | * so we can place orders. 159 | */ 160 | if ( LastValue(BuySignal) == True && isNewBar() ) 161 | { 162 | /* 163 | * We do some calculation to double the quantity, for all orders except first. 164 | * This is done so that we can re-enter a position. Following this approach 165 | * we can avoid using Short & Cover. 166 | */ 167 | quantity = calcDoubleQuantity(AT_ACCOUNT, AT_SYMBOL, AT_QUANTITY); 168 | 169 | placeOrder(AT_ACCOUNT, AT_EXCHANGE, AT_SYMBOL, "BUY", "MARKET", 170 | AT_PRODUCT_TYPE, quantity, buyPrice, defaultTriggerPrice(), True); 171 | } 172 | 173 | if ( LastValue(SellSignal) == True && isNewBar() ) 174 | { 175 | /* 176 | * We do some calculation to double the quantity, for all orders except first. 177 | * This is done so that we can re-enter a position. Following this approach 178 | * we can avoid using Short & Cover. 179 | */ 180 | quantity = calcDoubleQuantity(AT_ACCOUNT, AT_SYMBOL, AT_QUANTITY); 181 | 182 | placeOrder(AT_ACCOUNT, AT_EXCHANGE, AT_SYMBOL, "SELL", "MARKET", 183 | AT_PRODUCT_TYPE, quantity, sellPrice, defaultTriggerPrice(), True); 184 | } 185 | 186 | if(AT_PLACE_ORDER_ON_NEXT_BAR) { 187 | // Special handling when place order on next bar or candle is ON 188 | // This must be done after place order code 189 | 190 | if(LastValue(Buy) == True || LastValue(Sell) == True || 191 | LastValue(Short) == True || LastValue(Cover) == True) { 192 | // Save time of current bar when we get signal 193 | saveStaticVariable(AT_ACCOUNT, AT_PREVIOUS_BAR_END_TIME, Status( "lastbarend" )); 194 | } 195 | } 196 | 197 | } 198 | /******************************************************************** 199 | * SECTION 3 - END 200 | ********************************************************************/ 201 | 202 | _SECTION_END(); -------------------------------------------------------------------------------- /Formulas/AutoTraderWeb/General/at-target-sl-without-bo.afl: -------------------------------------------------------------------------------- 1 | /** 2 | * AmiBroker moving average with target & stoploss without using bracket order. 3 | * This is similar to placing a bracket order. Always use bracket order, 4 | * if it is available to you. Otherwise you can use this approach. 5 | * You need to set appropriate values in chart parameters. 6 | * 7 | * User Guide: https://stocksdeveloper.in/documentation/index/ 8 | * API Docs: https://stocksdeveloper.in/documentation/api/ 9 | * Symbol Search: https://stocksdeveloper.in:9013/instrument 10 | * 11 | * Author - Stocks Developer 12 | */ 13 | 14 | /******************************************************************** 15 | * SECTION 1 - BEGIN 16 | * This section contains all includes & should be at the top of your strategy afl. 17 | ********************************************************************/ 18 | 19 | #include 20 | #include 21 | 22 | /******************************************************************** 23 | * SECTION 1 - END 24 | ********************************************************************/ 25 | 26 | 27 | /******************************************************************* 28 | * This strategy demonstrates order operations. 29 | * 30 | * 31 | * Moving average crossover strategy. The rules are as follows: 32 | * 1. We enter into position only once. 33 | * 2. Once we enter a position, we place profit & stoploss orders. 34 | * 3. If profit order is complete, then we cancel stoploss order. 35 | * 4. If stoploss order is complete, then we cancel profit order. 36 | * 37 | * NOTE: This is similar to placing a bracket order. Always use bracket 38 | * order, if it is available to you. Otherwise you can use this approach. 39 | * 40 | * NOTE: It is recommended to start with a blank chart. 41 | ********************************************************************/ 42 | 43 | /******************************************************************* 44 | * How to see strategy logs in AMIBroker? 45 | * 1. Enable log window from amibroker menu (Window -> Log) 46 | * 2. You will see log window at the bottom. 47 | * 3. Go to "Trace" tab (all strategy logs are printed here). 48 | ********************************************************************/ 49 | 50 | 51 | /******************************************************************** 52 | * SECTION 2 - BEGIN 53 | * This section contains your strategy afl code. 54 | ********************************************************************/ 55 | 56 | /* 57 | * Calculates profit order price. 58 | */ 59 | function calculateProfitTarget(entryTradeType, entryPrice, profitPct) { 60 | result = 0; 61 | 62 | if(entryTradeType == "BUY" OR entryTradeType == "COVER") { 63 | result = entryPrice * (1 + (profitPct / 100)); 64 | } 65 | 66 | if(entryTradeType == "SELL" OR entryTradeType == "SHORT") { 67 | result = entryPrice * (1 - (profitPct / 100)); 68 | } 69 | 70 | return result; 71 | } 72 | 73 | /* 74 | * Calculates stoploss order price. 75 | */ 76 | function calculateStoplossTarget(entryTradeType, entryPrice, stoplossPct) { 77 | result = 0; 78 | 79 | if(entryTradeType == "BUY" OR entryTradeType == "COVER") { 80 | result = entryPrice * (1 - (stoplossPct / 100)); 81 | } 82 | 83 | if(entryTradeType == "SELL" OR entryTradeType == "SHORT") { 84 | result = entryPrice * (1 + (stoplossPct / 100)); 85 | } 86 | 87 | return result; 88 | } 89 | 90 | _SECTION_BEGIN("Moving Average"); 91 | 92 | // Moving Average 93 | SHORT_MA_PERIOD = Param("Short term moving average period", 20, 1, 200, 2); 94 | LONG_MA_PERIOD = Param("Long term moving average period", 40, 1, 200, 2); 95 | 96 | // Targets 97 | PROFIT_PCT = Param("Profit percentage", 1, 0.01, 20, 1); 98 | STOPLOSS_PCT = Param("Stoploss percentage", 1, 0.01, 20, 1); 99 | 100 | // Refresh even when minimized, see below link 101 | // https://forum.amibroker.com/t/program-pauses-when-amibroker-minimized/4145/2 102 | RefreshPeriod = Param( "Timed Refresh Period", 5, 1, 300); 103 | RequestTimedRefresh(RefreshPeriod, False); 104 | 105 | ENTRY_ORDER_KEY = "ENTRY_ORDER"; 106 | PROFIT_ORDER_KEY = "PROFIT_ORDER"; 107 | STOPLOSS_ORDER_KEY = "STOPLOSS_ORDER"; 108 | ENTRY_ORDER_TRADE_TYPE_KEY = "ENTRY_ORDER_TRADE_TYPE"; 109 | 110 | /* Exponential Moving averages */ 111 | EMA1 = EMA( C, SHORT_MA_PERIOD); 112 | EMA2 = EMA( C, LONG_MA_PERIOD); 113 | 114 | /* Buy and Sell Condition */ 115 | Buy = Cross(EMA1,EMA2); 116 | Sell = Cross(EMA2,EMA1); 117 | 118 | /* Remove excess signals */ 119 | Buy = ExRem(Buy,Sell); 120 | Sell = ExRem(Sell,Buy); 121 | 122 | /* Instead of using Short & Cover; we will double the quantity */ 123 | //Short = Sell; 124 | //Cover = Buy; 125 | 126 | /* Prices when Buy, Sell, Short, Cover condition is true */ 127 | //buyPrice = ValueWhen(Buy,C); 128 | //sellPrice = ValueWhen(Sell,C); 129 | 130 | /* We use live prices here, as ValueWhen function gives negative price sometimes */ 131 | buyPrice = LastValue(C); 132 | sellPrice = LastValue(C); 133 | 134 | /* Plot Buy and Sell Signal Arrows */ 135 | shape = Buy * shapeUpArrow + Sell * shapeDownArrow; 136 | PlotShapes( shape, IIf( Buy, colorGreen, colorRed ), 0, IIf( Buy, Low, High ) ); 137 | GraphXSpace = 5; 138 | 139 | /* Plot EMA lines and Candles */ 140 | Plot(EMA1,"EMA", colorRed); 141 | Plot(EMA2,"EMA2", colorGreen); 142 | Plot(C, "Close", colorRed, styleCandle); 143 | 144 | 145 | /******************************************************************** 146 | * SECTION 2 - END 147 | ********************************************************************/ 148 | 149 | 150 | /******************************************************************** 151 | * SECTION 3 - BEGIN 152 | * This section contains your code for placing orders. 153 | ********************************************************************/ 154 | 155 | /* 156 | * shouldSquareOff() returns True, when current time goes beyond square off time. 157 | */ 158 | if(shouldSquareOff()) { 159 | if(!isSquareOffRequestSent()) { 160 | // Square off position, as current time has gone passed square off time 161 | // Assuming the position is MIS 162 | squareOffPosition(AT_ACCOUNT, "DAY", "MIS", AT_EXCHANGE, AT_SYMBOL); 163 | 164 | saveStaticVariable(AT_ACCOUNT, AT_SQUARE_OFF_STATUS_KEY, 1); 165 | } 166 | } 167 | else { 168 | 169 | /***************************************************************** 170 | * ENTER INTO A POSITION 171 | *****************************************************************/ 172 | 173 | /* 174 | * isFirstOrder() returns True, if the order is the first of the day for the current chart. 175 | * We are using it here, to make sure we enter only once into a position. 176 | */ 177 | if(isFirstOrder(AT_ACCOUNT, AT_SYMBOL)) { 178 | 179 | if ( LastValue(Buy) == True ) 180 | { 181 | tradeType = "BUY"; 182 | orderId = placeOrder(AT_ACCOUNT, AT_EXCHANGE, AT_SYMBOL, tradeType, "MARKET", 183 | "INTRADAY", AT_QUANTITY, buyPrice, defaultTriggerPrice(), True); 184 | 185 | /* Save entry order id for later use */ 186 | saveStaticVariableText(AT_ACCOUNT, ENTRY_ORDER_KEY, orderId); 187 | saveStaticVariableText(AT_ACCOUNT, ENTRY_ORDER_TRADE_TYPE_KEY, tradeType); 188 | } 189 | 190 | if ( LastValue(Sell) == True ) 191 | { 192 | tradeType = "SELL"; 193 | orderId = placeOrder(AT_ACCOUNT, AT_EXCHANGE, AT_SYMBOL, tradeType, "MARKET", 194 | "INTRADAY", AT_QUANTITY, buyPrice, defaultTriggerPrice(), True); 195 | 196 | /* Save entry order id for later use */ 197 | saveStaticVariableText(AT_ACCOUNT, ENTRY_ORDER_KEY, orderId); 198 | saveStaticVariableText(AT_ACCOUNT, ENTRY_ORDER_TRADE_TYPE_KEY, tradeType); 199 | } 200 | } 201 | 202 | 203 | /***************************************************************** 204 | * ENTER PROFIT & STOPLOSS ORDERS 205 | *****************************************************************/ 206 | 207 | /* Get entry order id */ 208 | entryOrderId = readStaticVariableText(AT_ACCOUNT, ENTRY_ORDER_KEY); 209 | 210 | if(entryOrderId != "") { 211 | 212 | /* Check whether order status is complete */ 213 | if(isOrderComplete(AT_ACCOUNT, entryOrderId)) { 214 | 215 | /* Calculate exit order trade type */ 216 | entryTradeType = readStaticVariableText(AT_ACCOUNT, ENTRY_ORDER_TRADE_TYPE_KEY); 217 | exitTradeType = reverseTradeType(entryTradeType); 218 | 219 | /* Check whether we have already placed profit order */ 220 | if(readStaticVariableText(AT_ACCOUNT, PROFIT_ORDER_KEY) == "") { 221 | entryPrice = getOrderAveragePrice(AT_ACCOUNT, entryOrderId); 222 | message = "Entry order is complete, placing profit order. Entry order price: " + entryPrice; 223 | logInfo(message); 224 | _TRACE(message); 225 | 226 | if(entryPrice > 0) { 227 | profitPrice = calculateProfitTarget(entryTradeType, entryPrice, PROFIT_PCT); 228 | 229 | message = "Profit order price = " + profitPrice; 230 | logInfo(message); 231 | _TRACE(message); 232 | 233 | orderId = placeOrder(AT_ACCOUNT, AT_EXCHANGE, AT_SYMBOL, exitTradeType, "LIMIT", 234 | "INTRADAY", AT_QUANTITY, profitPrice, defaultTriggerPrice(), False); 235 | 236 | saveStaticVariableText(AT_ACCOUNT, PROFIT_ORDER_KEY, orderId); 237 | } else { 238 | message = "Profit order skipped, as entry order price is zero."; 239 | logInfo(message); 240 | _TRACE(message); 241 | } 242 | } 243 | 244 | /* Check whether we have already placed stoploss order */ 245 | if(readStaticVariableText(AT_ACCOUNT, STOPLOSS_ORDER_KEY) == "") { 246 | entryPrice = getOrderAveragePrice(AT_ACCOUNT, entryOrderId); 247 | message = "Entry order is complete, placing stoploss order. Entry order price: " + entryPrice; 248 | logInfo(message); 249 | _TRACE(message); 250 | 251 | if(entryPrice > 0) { 252 | triggerPrice = calculateStoplossTarget(entryTradeType, entryPrice, PROFIT_PCT); 253 | 254 | message = "Stoploss order trigger price = " + triggerPrice; 255 | logInfo(message); 256 | _TRACE(message); 257 | 258 | orderId = placeOrder(AT_ACCOUNT, AT_EXCHANGE, AT_SYMBOL, exitTradeType, "SL_MARKET", 259 | "INTRADAY", AT_QUANTITY, 0, triggerPrice, False); 260 | 261 | saveStaticVariableText(AT_ACCOUNT, STOPLOSS_ORDER_KEY, orderId); 262 | } else { 263 | message = "Stoploss order skipped, as entry order price is zero."; 264 | logInfo(message); 265 | _TRACE(message); 266 | } 267 | } 268 | } 269 | } 270 | 271 | 272 | /***************************************************************** 273 | * CANCEL OTHER ORDER WHEN EITHER PROFIT OR STOPLOSS IS HIT. 274 | *****************************************************************/ 275 | 276 | /* Get exit order ids */ 277 | profitOrderId = readStaticVariableText(AT_ACCOUNT, PROFIT_ORDER_KEY); 278 | stoplossOrderId = readStaticVariableText(AT_ACCOUNT, STOPLOSS_ORDER_KEY); 279 | 280 | /* Cancel stoploss order if profit order is complete */ 281 | if(isOrderComplete(AT_ACCOUNT, profitOrderId)) { 282 | if(isOrderOpen(AT_ACCOUNT, stoplossOrderId)) { 283 | message = "Profit order complete, cancelling stoploss order."; 284 | logInfo(message); 285 | _TRACE(message); 286 | cancelOrder(AT_ACCOUNT, stoplossOrderId); 287 | } 288 | } 289 | 290 | /* Cancel profit order if stoploss order is complete */ 291 | if(isOrderComplete(AT_ACCOUNT, stoplossOrderId)) { 292 | if(isOrderOpen(AT_ACCOUNT, profitOrderId)) { 293 | message = "Stoploss order complete, cancelling profit order."; 294 | logInfo(message); 295 | _TRACE(message); 296 | cancelOrder(AT_ACCOUNT, profitOrderId); 297 | } 298 | } 299 | 300 | } 301 | 302 | 303 | /******************************************************************** 304 | * SECTION 3 - END 305 | ********************************************************************/ 306 | 307 | _SECTION_END(); 308 | -------------------------------------------------------------------------------- /Formulas/Include/autotrader-api.afl: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * 3 | * AutoTrader automated trading API functions. 4 | * DO NOT MODIFY THIS FILE 5 | * Version: 3.0 6 | * 7 | ******************************************************************************/ 8 | 9 | /***************************** CONSTANTS - START *****************************/ 10 | 11 | AT_LAST_ORDER_TIME_KEY = "AT_LAST_ORDER_TIME"; 12 | AT_LAST_ORDER_TRADE_TYPE_KEY = "AT_LAST_ORDER_TRADE_TYPE"; 13 | 14 | AT_START_TIME_CHUNK = "globalStartTimeChunk"; 15 | AT_ORDER_SEQUENCE = "globalOrderSequence"; 16 | AT_INIT = "globalInit"; 17 | AT_GLOBAL_ORDER_NO_SEMAPHORE = "globalOrderNoSemaphore"; 18 | 19 | /****************************** CONSTANTS - END ******************************/ 20 | 21 | 22 | /***************************** PARAMETERS - START ****************************/ 23 | 24 | _SECTION_BEGIN("AutoTrader"); 25 | 26 | AT_EXCHANGE = ParamList("Exchange", "NSE|BSE|MCX"); 27 | 28 | AT_SYMBOL = ParamStr("Symbol", Name()); 29 | 30 | AT_ACCOUNT = ParamStr("Account", "Pseudo Account"); 31 | 32 | AT_PRODUCT_TYPE = ParamList("Product Type", "INTRADAY|DELIVERY|NORMAL"); 33 | 34 | AT_QUANTITY = Param("Quantity", 1, 0, 300000, 10); 35 | 36 | AT_USE_PRECISION = ParamToggle("Use price precision, used for rounding price", "OFF|ON", 0); 37 | 38 | AT_PRICE_PRECISION = StrToNum(ParamList( 39 | "Price precision, used for rounding price", "4|3|2|1|0")); 40 | 41 | AT_DEBUG = ParamToggle("Print Additional Logs", "OFF|ON", 0); 42 | 43 | /* 44 | * Used for avoiding repeat orders. Repeat orders are back to back buy or 45 | * sell orders. The system will not accept an order in this many seconds, 46 | * if an order for same stock, tradeType was sent earlier from the same chart. 47 | * If you want to execute back to back order then you can set this 48 | * parameter to 0. 49 | * If you want to avoid repeat orders generated due to duplicate signals 50 | * then set this parameter to a value higher than your candle interval. 51 | * 52 | * Example: 53 | * 1. Assume AT_AVOID_REPEAT_ORDER_DELAY value is set for 120 seconds & 54 | * your chart uses 1-minute (60 seconds) candle. 55 | * 2. System receives a BUY order for SBIN at time 10:15:15. 56 | * 3. System will place it. 57 | * 4. After 15 seconds, system receives another BUY order for SBIN 58 | * at time 10:15:30. 59 | * 5. The system will NOT place this order, as the symbol & tradeType 60 | * are same and the order came with 120 seconds of previous order. 61 | */ 62 | AT_AVOID_REPEAT_ORDER_DELAY = Param("Avoid repeat orders (in seconds)", 63 | 26000, 0, 26000, 5); 64 | 65 | _SECTION_END(); 66 | 67 | /***************************** PARAMETERS - END *****************************/ 68 | 69 | /* 70 | * Initialize static variable used for generating unique order number. 71 | */ 72 | if( Nz( StaticVarGet(AT_INIT) ) == 0 ) 73 | { 74 | StaticVarSet(AT_INIT, 1); 75 | 76 | // One time initialization 77 | StaticVarSet( AT_ORDER_SEQUENCE, 1); 78 | 79 | timestampChunk = (Now(5) / 1000000) % 1000000; 80 | startTime = NumToStr(timestampChunk, 1.0, False); 81 | StaticVarSetText( AT_START_TIME_CHUNK, startTime); 82 | } 83 | 84 | 85 | function nextGlobalOrderNumberInternal() { 86 | num = StaticVarGet( AT_ORDER_SEQUENCE ); 87 | StaticVarSet( AT_ORDER_SEQUENCE, num + 1); 88 | return num; 89 | } 90 | 91 | /* 92 | * Givens next global order number. 93 | */ 94 | function nextGlobalOrderNumber() { 95 | num = 0; 96 | if(tryEnterCriticalSection(AT_GLOBAL_ORDER_NO_SEMAPHORE)) 97 | { 98 | // you are inside critical section now 99 | num = nextGlobalOrderNumberInternal(); 100 | // Do not forget to leave critical section 101 | leaveCriticalSection(); 102 | } 103 | else 104 | { 105 | num = int((Random() * 100000) % 100000); 106 | } 107 | return num; 108 | } 109 | 110 | /* 111 | * Generates unique order id. 112 | */ 113 | function generateUniqueOrderId() { 114 | return StaticVarGetText(AT_START_TIME_CHUNK) + "-" + 115 | convertIntegerToString(nextGlobalOrderNumber()); 116 | } 117 | 118 | function accountSymbolKey(account, symbol) { 119 | return account + "-" + symbol; 120 | } 121 | 122 | /* 123 | * Saves last order time, in a static variable. 124 | */ 125 | procedure saveLastOrderTime(account, symbol, orderTime) { 126 | saveStaticVariable(accountSymbolKey(account, symbol), 127 | AT_LAST_ORDER_TIME_KEY, orderTime); 128 | } 129 | 130 | /* 131 | * Fetches the last order time (if available). 132 | */ 133 | function readLastOrderTime(account, symbol) { 134 | return readStaticVariable(accountSymbolKey(account, symbol), 135 | AT_LAST_ORDER_TIME_KEY); 136 | } 137 | 138 | /* 139 | * Saves last order trade type, in a static variable. 140 | */ 141 | procedure saveLastOrderTradeType(account, symbol, tradeType) { 142 | saveStaticVariableText(accountSymbolKey(account, symbol), 143 | AT_LAST_ORDER_TRADE_TYPE_KEY, StrToUpper(tradeType)); 144 | } 145 | 146 | /* 147 | * Fetches the last order trade type (if available). 148 | */ 149 | function readLastOrderTradeType(account, symbol) { 150 | return readStaticVariableText(accountSymbolKey(account, symbol), 151 | AT_LAST_ORDER_TRADE_TYPE_KEY); 152 | } 153 | 154 | /* 155 | * Converts order to easy to read text format. 156 | */ 157 | function orderString(variety, symbol, tradeType, orderType, quantity, 158 | price, triggerPrice, target, stoploss, trailingStoploss) { 159 | conciseForm = symbol + "|" + tradeType + "|" + orderType + "|" + 160 | quantity + "@" + price; 161 | 162 | if(variety == AT_VARIETY_BO) { 163 | result = "Bracket Order [" + conciseForm + "|" + 164 | "t=" + target + "|" + "sl=" + stoploss + "|" + 165 | "tr. sl=" + trailingStoploss + "]"; 166 | } else if (variety == AT_VARIETY_CO) { 167 | result = "Cover Order [" + conciseForm + "|" + "trigger=" + 168 | triggerPrice + "]"; 169 | } else { 170 | result = "Regular Order [" + conciseForm + "]"; 171 | } 172 | 173 | return result; 174 | } 175 | 176 | /* 177 | * Checks whether we have a duplicate signal. This is done to overcome a limitation 178 | * in AmiBroker, which keeps on giving same signal for every tick 179 | * until the candle is complete. 180 | */ 181 | function isDuplicateSignal(account, tradeType, symbol) { 182 | duplicate = False; 183 | 184 | time = readLastOrderTime(account, symbol); 185 | lastTradeType = readLastOrderTradeType(account, symbol); 186 | 187 | if(time > 0) { 188 | difference = DateTimeDiff(Now(5), time); 189 | 190 | if(difference < AT_AVOID_REPEAT_ORDER_DELAY AND 191 | lastTradeType == StrToUpper(tradeType)) { 192 | 193 | message = "ERROR: Duplicate signal. Previous order = " 194 | + lastTradeType + ", Current order = " + tradeType; 195 | logError(message); 196 | _TRACE(message); 197 | 198 | if(AT_DEBUG) { 199 | message = "Last order time is = " + DateTimeToStr(time); 200 | logDebug(message); 201 | _TRACE(message); 202 | 203 | message = "Difference of [" + difference + 204 | "] seconds is less than avoid duplicate order duration of [" 205 | + AT_AVOID_REPEAT_ORDER_DELAY + "] seconds."; 206 | logDebug(message); 207 | _TRACE(message); 208 | } 209 | 210 | duplicate = True; 211 | } 212 | } 213 | 214 | return duplicate; 215 | } 216 | 217 | /*****************************************************************************/ 218 | /*********************** PLACE ORDER FUNCTIONS - START ***********************/ 219 | /*****************************************************************************/ 220 | 221 | /* 222 | * An advanced function to place orders. 223 | */ 224 | function placeOrderAdvanced(variety, account, exchange, symbol, 225 | tradeType, orderType, productType, 226 | quantity, price, triggerPrice, 227 | target, stoploss, trailingStoploss, 228 | disclosedQuantity, validity, amo, 229 | strategyId, comments, validate) { 230 | 231 | // Initially order id is blank 232 | orderId = ""; 233 | 234 | orderStr = orderString(variety, symbol, tradeType, orderType, quantity, 235 | price, triggerPrice, target, stoploss, trailingStoploss); 236 | 237 | if(AT_DEBUG) { 238 | message = "Placing order: " + orderStr; 239 | logDebug(message); 240 | _TRACE(message); 241 | } 242 | 243 | proceed = TRUE; 244 | if(validate) { 245 | // Perform validation 246 | 247 | // Perform duplicate signal check 248 | if(isDuplicateSignal(account, tradeType, symbol)) { 249 | message = "Order failed validation: " + orderStr; 250 | logError(message); 251 | _TRACE(message); 252 | 253 | proceed = False; 254 | } 255 | } 256 | 257 | if(proceed) { 258 | 259 | // Generate unique order id 260 | orderId = generateUniqueOrderId(); 261 | 262 | // Save order generation time 263 | publishTime = convertIntegerToString( 264 | convertDateTimeToMillisSinceEpoch(LastValue(DateTime()))); 265 | 266 | // Convert data into text in order to write it to a CSV file 267 | 268 | if(AT_USE_PRECISION) { 269 | priceStr = StrFormat("%.5f", prec( 270 | IIF( price < 0, 0, price ), AT_PRICE_PRECISION)); 271 | triggerPriceStr = StrFormat("%.5f", prec( 272 | IIF( triggerPrice < 0, 0, triggerPrice ), AT_PRICE_PRECISION)); 273 | targetStr = StrFormat("%.5f", prec( 274 | IIF( target < 0, 0, target ), AT_PRICE_PRECISION)); 275 | stoplossStr = StrFormat("%.5f", prec( 276 | IIF( stoploss < 0, 0, stoploss ), AT_PRICE_PRECISION)); 277 | trailingStoplossStr = StrFormat("%.5f", prec( 278 | IIF( trailingStoploss < 0, 0, trailingStoploss ), 279 | AT_PRICE_PRECISION)); 280 | } else { 281 | priceStr = NumToStr( price, 1.4, False ); 282 | triggerPriceStr = NumToStr( triggerPrice, 1.4, False ); 283 | targetStr = NumToStr( target, 1.4, False ); 284 | stoplossStr = NumToStr( stoploss, 1.4, False ); 285 | trailingStoplossStr = NumToStr( trailingStoploss, 1.4, False ); 286 | } 287 | 288 | 289 | if(amo) { 290 | amoStr = "true"; 291 | } else { 292 | amoStr = "false"; 293 | } 294 | 295 | // Handling for a comma in comments 296 | commentsStr = StrReplace(comments, AT_COMMA, ";" ); 297 | 298 | csv = AT_PLACE_ORDER_CMD + AT_COMMA + 299 | account + AT_COMMA + 300 | orderId + AT_COMMA + 301 | variety + AT_COMMA + 302 | exchange + AT_COMMA + 303 | symbol + AT_COMMA + 304 | tradeType + AT_COMMA + 305 | orderType + AT_COMMA + 306 | productType + AT_COMMA + 307 | quantity + AT_COMMA + 308 | priceStr + AT_COMMA + 309 | triggerPriceStr + AT_COMMA + 310 | targetStr + AT_COMMA + 311 | stoplossStr + AT_COMMA + 312 | trailingStoplossStr + AT_COMMA + 313 | disclosedQuantity + AT_COMMA + 314 | validity + AT_COMMA + 315 | amoStr + AT_COMMA + 316 | publishTime + AT_COMMA + 317 | strategyId + AT_COMMA + 318 | comments; 319 | 320 | if(AT_DEBUG) { 321 | message = "Order csv data: " + csv; 322 | logDebug(message); 323 | _TRACE(message); 324 | } 325 | 326 | written = fileWriteLine(COMMANDS_FILE, csv); 327 | 328 | if(written) { 329 | saveLastOrderTradeType(account, symbol, tradeType); 330 | saveLastOrderTime(account, symbol, Now(5)); 331 | 332 | message = "Order placed: [" + orderStr + "], order id: " + orderId; 333 | logInfo(message); 334 | _TRACE(message); 335 | } else { 336 | message = "ERROR: Order placement failed: [" + orderStr + "]"; 337 | logError(message); 338 | _TRACE(message); 339 | 340 | message = "Either the commands file is missing or it is locked by another application."; 341 | logError(message); 342 | _TRACE(message); 343 | 344 | message = "Kindly check the communication folder path in at-desktop settings."; 345 | logError(message); 346 | _TRACE(message); 347 | 348 | message = "Communication path should be: " + IPC_DIR; 349 | logError(message); 350 | _TRACE(message); 351 | 352 | orderId = ""; 353 | } 354 | } 355 | 356 | return orderId; 357 | } 358 | 359 | /* 360 | * A function to place regular orders. Returns order id on successful 361 | * order placement; otherwise returns blank. 362 | * 363 | * If a parameter is not applicable, then either pass blank (for text parameter) 364 | * or zero (for numeric parameter). 365 | */ 366 | function placeOrder(account, exchange, symbol, tradeType, orderType, 367 | productType, quantity, price, triggerPrice, validate) { 368 | 369 | return placeOrderAdvanced(defaultVariety(), account, exchange, symbol, 370 | tradeType, orderType, productType, 371 | quantity, price, triggerPrice, 372 | defaultTarget(), defaultStoploss(), defaultTrailingStoploss(), 373 | defaultDisclosedQuantity(), defaultValidity(), defaultAmo(), 374 | defaultStrategyId(), defaultComments(), validate); 375 | 376 | } 377 | 378 | /* 379 | * A function to place bracket orders.Returns order id on successful 380 | * order placement; otherwise returns blank. 381 | * 382 | * If a parameter is not applicable, then either pass blank (for text parameter) 383 | * or zero (for numeric parameter). 384 | */ 385 | function placeBracketOrder(account, exchange, symbol, tradeType, orderType, 386 | quantity, price, triggerPrice, target, stoploss, trailingStoploss, validate) { 387 | 388 | return placeOrderAdvanced(AT_VARIETY_BO, account, exchange, symbol, 389 | tradeType, orderType, AT_PRODUCT_INTRADAY, 390 | quantity, price, triggerPrice, 391 | target, stoploss, trailingStoploss, 392 | defaultDisclosedQuantity(), defaultValidity(), defaultAmo(), 393 | defaultStrategyId(), defaultComments(), validate); 394 | 395 | } 396 | 397 | /* 398 | * A function to place cover orders.Returns order id on successful 399 | * order placement; otherwise returns blank. 400 | * 401 | * If a parameter is not applicable, then either pass blank (for text parameter) 402 | * or zero (for numeric parameter). 403 | */ 404 | function placeCoverOrder(account, exchange, symbol, tradeType, orderType, 405 | quantity, price, triggerPrice, validate) { 406 | 407 | return placeOrderAdvanced(AT_VARIETY_CO, account, exchange, symbol, 408 | tradeType, orderType, AT_PRODUCT_INTRADAY, 409 | quantity, price, triggerPrice, 410 | defaultTarget(), defaultStoploss(), defaultTrailingStoploss(), 411 | defaultDisclosedQuantity(), defaultValidity(), defaultAmo(), 412 | defaultStrategyId(), defaultComments(), validate); 413 | 414 | } 415 | 416 | /*****************************************************************************/ 417 | /************************ PLACE ORDER FUNCTIONS - END ************************/ 418 | /*****************************************************************************/ 419 | 420 | 421 | /*****************************************************************************/ 422 | /*********************** MODIFY ORDER FUNCTIONS - START **********************/ 423 | /*****************************************************************************/ 424 | 425 | procedure printOrderModification(account, orderId, orderType, quantity, 426 | price, triggerPrice) { 427 | 428 | message = "Modification: "; 429 | message += ("[Account = " + account + "]"); 430 | message += ("[Order Id = " + orderId + "]"); 431 | 432 | if(orderType != "") { 433 | message += ("[OrderType = " + orderType + "]"); 434 | } 435 | 436 | if(quantity > 0) { 437 | message += ("[Quantity = " + quantity + "]"); 438 | } 439 | 440 | if(price > 0) { 441 | message += ("[Price = " + price + "]"); 442 | } 443 | 444 | if(triggerPrice > 0) { 445 | message += ("[Trigger Price = " + triggerPrice + "]"); 446 | } 447 | 448 | logDebug(message); 449 | _TRACE(message); 450 | } 451 | 452 | /** 453 | * Modifies the order. Returns True on successful modification request; 454 | * otherwise returns False. 455 | * 456 | * If a parameter is not applicable, then either pass blank (for text parameter) 457 | * or zero (for numeric parameter). 458 | */ 459 | function modifyOrder(account, orderId, orderType, quantity, price, 460 | triggerPrice) { 461 | 462 | if(AT_USE_PRECISION) { 463 | priceStr = StrFormat("%.5f", prec(price, AT_PRICE_PRECISION)); 464 | triggerPriceStr = StrFormat("%.5f", 465 | prec(triggerPrice, AT_PRICE_PRECISION)); 466 | } else { 467 | priceStr = NumToStr( price, 1.4, False ); 468 | triggerPriceStr = NumToStr( triggerPrice, 1.4, False ); 469 | } 470 | 471 | csv = AT_MODIFY_ORDER_CMD + AT_COMMA + 472 | account + AT_COMMA + 473 | orderId + AT_COMMA + 474 | orderType + AT_COMMA + 475 | quantity + AT_COMMA + 476 | priceStr + AT_COMMA + 477 | triggerPriceStr; 478 | 479 | if(AT_DEBUG) { 480 | message = "Sending order modify request: " + csv; 481 | logDebug(message); 482 | _TRACE(message); 483 | } 484 | 485 | written = fileWriteLine(COMMANDS_FILE, csv); 486 | 487 | printOrderModification(account, orderId, orderType, quantity, price, 488 | triggerPrice); 489 | 490 | if(written) { 491 | message = "Order modify request sent. Command: " + csv; 492 | logDebug(message); 493 | _TRACE(message); 494 | } else { 495 | message = "Order modify request failed. Command: " + csv; 496 | logError(message); 497 | _TRACE(message); 498 | } 499 | 500 | return written; 501 | } 502 | 503 | function modifyOrderPrice(account, orderId, price) { 504 | return modifyOrder(account, orderId, AT_BLANK, 0, price, 0); 505 | } 506 | 507 | function modifyOrderQuantity(account, orderId, quantity) { 508 | return modifyOrder(account, orderId, AT_BLANK, quantity, 0, 0); 509 | } 510 | 511 | /*****************************************************************************/ 512 | /************************ MODIFY ORDER FUNCTIONS - END ***********************/ 513 | /*****************************************************************************/ 514 | 515 | 516 | /*****************************************************************************/ 517 | /*********************** CANCEL/EXIT ORDER FUNCTIONS - START **********************/ 518 | /*****************************************************************************/ 519 | 520 | /* 521 | * Sends cancel order request to AutoTrader. Pass account & order id. Returns true on success. 522 | */ 523 | function cancelOrder(account, id) { 524 | if(AT_DEBUG) { 525 | message = "Cancelling order, order id: " + id; 526 | logDebug(message); 527 | _TRACE(message); 528 | } 529 | 530 | csv = AT_CANCEL_ORDER_CMD + AT_COMMA + 531 | account + AT_COMMA + 532 | id; 533 | 534 | written = fileWriteLine(COMMANDS_FILE, csv); 535 | 536 | if(written) { 537 | message = "Order cancel request sent, order id: " + id; 538 | logDebug(message); 539 | _TRACE(message); 540 | } else { 541 | message = "Order cancel request failed, order id: " + id; 542 | logError(message); 543 | _TRACE(message); 544 | } 545 | 546 | return written; 547 | } 548 | 549 | /* 550 | * Cancels child orders of a bracket or cover order. 551 | * This function is useful for exiting from bracket and cover order. 552 | * Pass the account & id you received after placing a bracket or cover order. 553 | */ 554 | function cancelOrderChildren(account, id) { 555 | if(AT_DEBUG) { 556 | message = "Inside cancelOrderChildren, order id: " + id; 557 | logDebug(message); 558 | _TRACE(message); 559 | } 560 | 561 | csv = AT_CANCEL_CHILD_ORDER_CMD + AT_COMMA + 562 | account + AT_COMMA + 563 | id; 564 | 565 | written = fileWriteLine(COMMANDS_FILE, csv); 566 | 567 | if(written) { 568 | message = "Order cancel children request sent, order id: " + id; 569 | logDebug(message); 570 | _TRACE(message); 571 | } else { 572 | message = "Order cancel children request failed, order id: " + id; 573 | logError(message); 574 | _TRACE(message); 575 | } 576 | 577 | return written; 578 | } 579 | 580 | /* 581 | * Cancels or exits from order. This function is useful for exiting from bracket and cover order. 582 | * If the order is OPEN, it will be cancelled. If it is executed, system will cancel it's child orders; 583 | * which will result in exiting the position. 584 | * Pass account & id you received after placing a bracket or cover order. 585 | */ 586 | function cancelOrExitOrder(account, id) { 587 | if(AT_DEBUG) { 588 | message = "Inside cancelOrExitOrder, order id = " + id; 589 | logDebug(message); 590 | _TRACE(message); 591 | } 592 | 593 | // Cancel the Bracket order if it is open 594 | cancelOrder(account, id); 595 | 596 | // Exit from bracket order 597 | cancelOrderChildren(account, id); 598 | } 599 | 600 | /* 601 | * Cancels all open orders for the given account. Returns true on success. 602 | */ 603 | function cancelAllOrders(account) { 604 | if(AT_DEBUG) { 605 | message = "Cancelling all open orders for account: " + account; 606 | logDebug(message); 607 | _TRACE(message); 608 | } 609 | 610 | csv = AT_CANCEL_ALL_ORDERS_CMD + AT_COMMA + account; 611 | 612 | written = fileWriteLine(COMMANDS_FILE, csv); 613 | 614 | if(written) { 615 | message = "Cancel all open orders request sent, account: " + account; 616 | logDebug(message); 617 | _TRACE(message); 618 | } else { 619 | message = "Cancel all open orders request failed, account: " + account; 620 | logError(message); 621 | _TRACE(message); 622 | } 623 | 624 | return written; 625 | } 626 | 627 | /*****************************************************************************/ 628 | /************************ CANCEL/EXIT ORDER FUNCTIONS - END ***********************/ 629 | /*****************************************************************************/ 630 | 631 | 632 | /*****************************************************************************/ 633 | /************************ SQUARE OFF FUNCTIONS - START ***********************/ 634 | /*****************************************************************************/ 635 | 636 | /** 637 | * Submits a square-off request for the given position. 638 | * 639 | * pseudoAccount - account to which the position belongs 640 | * category - position category (DAY, NET). Pass DAY if you are not sure. 641 | * type - position type (MIS, NRML, CNC, BO, CO) 642 | * independentExchange - broker independent exchange 643 | * independentSymbol - broker independent symbol 644 | */ 645 | function squareOffPosition(pseudoAccount, category, type, 646 | independentExchange, independentSymbol) { 647 | 648 | positionStr = pseudoAccount + AT_PIPE + 649 | category + AT_PIPE + 650 | type + AT_PIPE + 651 | independentExchange + AT_PIPE + 652 | independentSymbol; 653 | 654 | if(AT_DEBUG) { 655 | message = "Inside squareOffPosition, position: [" + positionStr + "]"; 656 | logDebug(message); 657 | _TRACE(message); 658 | } 659 | 660 | csv = AT_SQUARE_OFF_POSITION + AT_COMMA + 661 | pseudoAccount + AT_COMMA + 662 | category + AT_COMMA + 663 | type + AT_COMMA + 664 | independentExchange + AT_COMMA + 665 | independentSymbol; 666 | 667 | written = fileWriteLine(COMMANDS_FILE, csv); 668 | 669 | if(written) { 670 | message = "Square-off position request sent. Position: [" + positionStr + "]"; 671 | logDebug(message); 672 | _TRACE(message); 673 | } else { 674 | message = "Square-off position request failed. Position: [" + positionStr + "]"; 675 | logError(message); 676 | _TRACE(message); 677 | } 678 | 679 | return written; 680 | } 681 | 682 | /** 683 | * Submits a square-off request for the given account. 684 | * Server will square-off all open positions in the given account. 685 | * 686 | * pseudoAccount - account to which the position belongs 687 | * category - position category (DAY, NET). Pass DAY if you are not sure. 688 | */ 689 | function squareOffPortfolio(pseudoAccount, category) { 690 | 691 | portfolioStr = pseudoAccount + AT_PIPE + 692 | category; 693 | 694 | if(AT_DEBUG) { 695 | message = "Inside squareOffPortfolio, portfolio: [" + portfolioStr + "]"; 696 | logDebug(message); 697 | _TRACE(message); 698 | } 699 | 700 | csv = AT_SQUARE_OFF_PORTFOLIO + AT_COMMA + 701 | pseudoAccount + AT_COMMA + 702 | category; 703 | 704 | written = fileWriteLine(COMMANDS_FILE, csv); 705 | 706 | if(written) { 707 | message = "Square-off portfolio request sent. Portfolio: [" + portfolioStr + "]"; 708 | logDebug(message); 709 | _TRACE(message); 710 | } else { 711 | message = "Square-off portfolio request failed. Portfolio: [" + portfolioStr + "]"; 712 | logError(message); 713 | _TRACE(message); 714 | } 715 | 716 | return written; 717 | } 718 | 719 | /*****************************************************************************/ 720 | /************************ SQUARE OFF FUNCTIONS - END ***********************/ 721 | /*****************************************************************************/ 722 | 723 | 724 | /*****************************************************************************/ 725 | /************************ ORDER DETAIL FUNCTIONS - START ***********************/ 726 | /*****************************************************************************/ 727 | 728 | /* 729 | * Reads orders file and returns a column value for the given order id. 730 | */ 731 | function readOrderColumn(pseudoAccount, orderId, columnIndex) { 732 | filePath = getPortfolioOrdersFile(pseudoAccount); 733 | return fileReadCsvColumnByRowId( filePath, orderId, 3, columnIndex ); 734 | } 735 | 736 | /* 737 | * Retrieve order's trading account. 738 | */ 739 | function getOrderTradingAccount(pseudoAccount, orderId) { 740 | return readOrderColumn(pseudoAccount, orderId, 2); 741 | } 742 | 743 | /* 744 | * Retrieve order's trading platform id. 745 | */ 746 | function getOrderId(pseudoAccount, orderId) { 747 | return readOrderColumn(pseudoAccount, orderId, 4); 748 | } 749 | 750 | /* 751 | * Retrieve order's exchange id. 752 | */ 753 | function getOrderExchangeId(pseudoAccount, orderId) { 754 | return readOrderColumn(pseudoAccount, orderId, 5); 755 | } 756 | 757 | /* 758 | * Retrieve order's variety (REGULAR, BO, CO). 759 | */ 760 | function getOrderVariety(pseudoAccount, orderId) { 761 | return readOrderColumn(pseudoAccount, orderId, 6); 762 | } 763 | 764 | /* 765 | * Retrieve order's (platform independent) exchange. 766 | */ 767 | function getOrderIndependentExchange(pseudoAccount, orderId) { 768 | return readOrderColumn(pseudoAccount, orderId, 7); 769 | } 770 | 771 | /* 772 | * Retrieve order's (platform independent) symbol. 773 | */ 774 | function getOrderIndependentSymbol(pseudoAccount, orderId) { 775 | return readOrderColumn(pseudoAccount, orderId, 8); 776 | } 777 | 778 | /* 779 | * Retrieve order's trade type (BUY, SELL). 780 | */ 781 | function getOrderTradeType(pseudoAccount, orderId) { 782 | return readOrderColumn(pseudoAccount, orderId, 9); 783 | } 784 | 785 | /* 786 | * Retrieve order's order type (LIMIT, MARKET, STOP_LOSS, SL_MARKET). 787 | */ 788 | function getOrderOrderType(pseudoAccount, orderId) { 789 | return readOrderColumn(pseudoAccount, orderId, 10); 790 | } 791 | 792 | /* 793 | * Retrieve order's product type (INTRADAY, DELIVERY, NORMAL). 794 | */ 795 | function getOrderProductType(pseudoAccount, orderId) { 796 | return readOrderColumn(pseudoAccount, orderId, 11); 797 | } 798 | 799 | /* 800 | * Retrieve order's quantity. 801 | */ 802 | function getOrderQuantity(pseudoAccount, orderId) { 803 | return StrToNum(readOrderColumn(pseudoAccount, orderId, 12)); 804 | } 805 | 806 | /* 807 | * Retrieve order's price. 808 | */ 809 | function getOrderPrice(pseudoAccount, orderId) { 810 | return StrToNum(readOrderColumn(pseudoAccount, orderId, 13)); 811 | } 812 | 813 | /* 814 | * Retrieve order's trigger price. 815 | */ 816 | function getOrderTriggerPrice(pseudoAccount, orderId) { 817 | return StrToNum(readOrderColumn(pseudoAccount, orderId, 14)); 818 | } 819 | 820 | /* 821 | * Retrieve order's filled quantity. 822 | */ 823 | function getOrderFilledQuantity(pseudoAccount, orderId) { 824 | return StrToNum(readOrderColumn(pseudoAccount, orderId, 15)); 825 | } 826 | 827 | /* 828 | * Retrieve order's pending quantity. 829 | */ 830 | function getOrderPendingQuantity(pseudoAccount, orderId) { 831 | return StrToNum(readOrderColumn(pseudoAccount, orderId, 16)); 832 | } 833 | 834 | /* 835 | * Retrieve order's (platform independent) status. 836 | * (OPEN, COMPLETE, CANCELLED, REJECTED, TRIGGER_PENDING, UNKNOWN) 837 | */ 838 | function getOrderStatus(pseudoAccount, orderId) { 839 | return readOrderColumn(pseudoAccount, orderId, 17); 840 | } 841 | 842 | /* 843 | * Retrieve order's status message or rejection reason. 844 | */ 845 | function getOrderStatusMessage(pseudoAccount, orderId) { 846 | return readOrderColumn(pseudoAccount, orderId, 18); 847 | } 848 | 849 | /* 850 | * Retrieve order's validity (DAY, IOC). 851 | */ 852 | function getOrderValidity(pseudoAccount, orderId) { 853 | return readOrderColumn(pseudoAccount, orderId, 19); 854 | } 855 | 856 | /* 857 | * Retrieve order's average price at which it got traded. 858 | */ 859 | function getOrderAveragePrice(pseudoAccount, orderId) { 860 | return StrToNum(readOrderColumn(pseudoAccount, orderId, 20)); 861 | } 862 | 863 | /* 864 | * Retrieve order's parent order id. The id of parent bracket or cover order. 865 | */ 866 | function getOrderParentOrderId(pseudoAccount, orderId) { 867 | return readOrderColumn(pseudoAccount, orderId, 21); 868 | } 869 | 870 | /* 871 | * Retrieve order's disclosed quantity. 872 | */ 873 | function getOrderDisclosedQuantity(pseudoAccount, orderId) { 874 | return StrToNum(readOrderColumn(pseudoAccount, orderId, 22)); 875 | } 876 | 877 | /* 878 | * Retrieve order's exchange time as a string (YYYY-MM-DD HH:MM:SS.MILLIS). 879 | */ 880 | function getOrderExchangeTime(pseudoAccount, orderId) { 881 | return readOrderColumn(pseudoAccount, orderId, 23); 882 | } 883 | 884 | /* 885 | * Retrieve order's platform time as a string (YYYY-MM-DD HH:MM:SS.MILLIS). 886 | */ 887 | function getOrderPlatformTime(pseudoAccount, orderId) { 888 | return readOrderColumn(pseudoAccount, orderId, 24); 889 | } 890 | 891 | /* 892 | * Retrieve order's AMO (after market order) flag. (true/false) 893 | */ 894 | function getOrderAmo(pseudoAccount, orderId) { 895 | flag = readOrderColumn(pseudoAccount, orderId, 25); 896 | return (StrToLower(flag) == "true"); 897 | } 898 | 899 | /* 900 | * Retrieve order's comments. 901 | */ 902 | function getOrderComments(pseudoAccount, orderId) { 903 | return readOrderColumn(pseudoAccount, orderId, 26); 904 | } 905 | 906 | /* 907 | * Retrieve order's raw (platform specific) status. 908 | */ 909 | function getOrderRawStatus(pseudoAccount, orderId) { 910 | return readOrderColumn(pseudoAccount, orderId, 27); 911 | } 912 | 913 | /* 914 | * Retrieve order's (platform specific) exchange. 915 | */ 916 | function getOrderExchange(pseudoAccount, orderId) { 917 | return readOrderColumn(pseudoAccount, orderId, 28); 918 | } 919 | 920 | /* 921 | * Retrieve order's (platform specific) symbol. 922 | */ 923 | function getOrderSymbol(pseudoAccount, orderId) { 924 | return readOrderColumn(pseudoAccount, orderId, 29); 925 | } 926 | 927 | /* 928 | * Retrieve order's date (DD-MM-YYYY). 929 | */ 930 | function getOrderDay(pseudoAccount, orderId) { 931 | return readOrderColumn(pseudoAccount, orderId, 30); 932 | } 933 | 934 | /* 935 | * Retrieve order's trading platform. 936 | */ 937 | function getOrderPlatform(pseudoAccount, orderId) { 938 | return readOrderColumn(pseudoAccount, orderId, 31); 939 | } 940 | 941 | /* 942 | * Retrieve order's client id (as received from trading platform). 943 | */ 944 | function getOrderClientId(pseudoAccount, orderId) { 945 | return readOrderColumn(pseudoAccount, orderId, 32); 946 | } 947 | 948 | /* 949 | * Retrieve order's stock broker. 950 | */ 951 | function getOrderStockBroker(pseudoAccount, orderId) { 952 | return readOrderColumn(pseudoAccount, orderId, 33); 953 | } 954 | 955 | /* 956 | * Checks whether order is open. 957 | * orderId - should be the id returned by placeOrder function when you place an order. 958 | */ 959 | function isOrderOpen(pseudoAccount, orderId) { 960 | oStatus = getOrderStatus(pseudoAccount, orderId); 961 | return (StrToUpper(oStatus) == "OPEN" OR StrToUpper(oStatus) == "TRIGGER_PENDING"); 962 | } 963 | 964 | /* 965 | * Checks whether order is complete. 966 | * orderId - should be the id returned by placeOrder function when you place an order. 967 | */ 968 | function isOrderComplete(pseudoAccount, orderId) { 969 | oStatus = getOrderStatus(pseudoAccount, orderId); 970 | return StrToUpper(oStatus) == "COMPLETE"; 971 | } 972 | 973 | /* 974 | * Checks whether order is rejected. 975 | * id - should be the id returned by placeOrder function when you place an order. 976 | */ 977 | function isOrderRejected(pseudoAccount, orderId) { 978 | oStatus = getOrderStatus(pseudoAccount, orderId); 979 | return StrToUpper(oStatus) == "REJECTED"; 980 | } 981 | 982 | /* 983 | * Checks whether order is cancelled. 984 | * id - should be the id returned by placeOrder function when you place an order. 985 | */ 986 | function isOrderCancelled(pseudoAccount, orderId) { 987 | oStatus = getOrderStatus(pseudoAccount, orderId); 988 | return StrToUpper(oStatus) == "CANCELLED"; 989 | } 990 | 991 | /*****************************************************************************/ 992 | /************************ ORDER DETAIL FUNCTIONS - END ***********************/ 993 | /*****************************************************************************/ 994 | 995 | 996 | /*****************************************************************************/ 997 | /************************ POSITION DETAIL FUNCTIONS - START ***********************/ 998 | /*****************************************************************************/ 999 | 1000 | /* 1001 | * Reads positions file and returns a column value for the given position id. 1002 | * Position id is a combination of category, type, independentExchange & independentSymbol. 1003 | */ 1004 | function readPositionColumnInternal(pseudoAccount, 1005 | category, categoryColumnIndex, type, typeColumnIndex, 1006 | independentExchange, independentExchangeColumnIndex, 1007 | independentSymbol, independentSymbolColumnIndex, columnIndex) { 1008 | 1009 | filePath = getPortfolioPositionsFile(pseudoAccount); 1010 | 1011 | fh = fopen( filePath, FILE_DEFAULT_READ_MODE ); 1012 | result = ""; 1013 | 1014 | if( fh ) 1015 | { 1016 | for( i = 0; ! feof( fh ) AND i < FILE_DEFAULT_MAX_LINES_SAFETY_CHECK; i++ ) 1017 | { 1018 | // read a line of text 1019 | line = fgets( fh ); 1020 | 1021 | if( line == "" ) 1022 | { 1023 | // Continue if we encounter a blank line 1024 | continue; 1025 | } 1026 | 1027 | if( category == StrExtract( line, categoryColumnIndex - 1 ) AND 1028 | type == StrExtract( line, typeColumnIndex - 1 ) AND 1029 | independentExchange == StrExtract( line, independentExchangeColumnIndex - 1 ) AND 1030 | independentSymbol == StrExtract( line, independentSymbolColumnIndex - 1 ) ) { 1031 | 1032 | result = StrExtract( line, columnIndex - 1 ); 1033 | break; 1034 | } 1035 | } 1036 | 1037 | fclose( fh ); 1038 | } 1039 | else 1040 | { 1041 | message = "ERROR: file can not be found " + filePath; 1042 | logError(message); 1043 | _TRACE(message); 1044 | } 1045 | 1046 | return result; 1047 | } 1048 | 1049 | /* 1050 | * Reads positions file and returns a column value for the given position id. 1051 | * Position id is a combination of category, type, independentExchange & independentSymbol. 1052 | */ 1053 | function readPositionColumn(pseudoAccount, 1054 | category, type, independentExchange, independentSymbol, columnIndex) { 1055 | 1056 | return readPositionColumnInternal(pseudoAccount, category, 4, type, 3, 1057 | independentExchange, 5, independentSymbol, 6, columnIndex); 1058 | } 1059 | 1060 | /* 1061 | * Retrieve positions's trading account. 1062 | */ 1063 | function getPositionTradingAccount(pseudoAccount, category, type, 1064 | independentExchange, independentSymbol) { 1065 | return readPositionColumn(pseudoAccount, 1066 | category, type, independentExchange, independentSymbol, 2); 1067 | } 1068 | 1069 | /* 1070 | * Retrieve positions's MTM (Mtm calculated by your stock broker). 1071 | */ 1072 | function getPositionMtm(pseudoAccount, category, type, 1073 | independentExchange, independentSymbol) { 1074 | return StrToNum(readPositionColumn(pseudoAccount, 1075 | category, type, independentExchange, independentSymbol, 7)); 1076 | } 1077 | 1078 | /* 1079 | * Retrieve positions's PNL (Pnl calculated by your stock broker). 1080 | */ 1081 | function getPositionPnl(pseudoAccount, category, type, 1082 | independentExchange, independentSymbol) { 1083 | return StrToNum(readPositionColumn(pseudoAccount, 1084 | category, type, independentExchange, independentSymbol, 8)); 1085 | } 1086 | 1087 | /* 1088 | * Retrieve positions's AT PNL (Pnl calculated by AutoTrader Web). 1089 | */ 1090 | function getPositionAtPnl(pseudoAccount, category, type, 1091 | independentExchange, independentSymbol) { 1092 | return StrToNum(readPositionColumn(pseudoAccount, 1093 | category, type, independentExchange, independentSymbol, 31)); 1094 | } 1095 | 1096 | /* 1097 | * Retrieve positions's buy quantity. 1098 | */ 1099 | function getPositionBuyQuantity(pseudoAccount, category, type, 1100 | independentExchange, independentSymbol) { 1101 | return StrToNum(readPositionColumn(pseudoAccount, 1102 | category, type, independentExchange, independentSymbol, 9)); 1103 | } 1104 | 1105 | /* 1106 | * Retrieve positions's sell quantity. 1107 | */ 1108 | function getPositionSellQuantity(pseudoAccount, category, type, 1109 | independentExchange, independentSymbol) { 1110 | return StrToNum(readPositionColumn(pseudoAccount, 1111 | category, type, independentExchange, independentSymbol, 10)); 1112 | } 1113 | 1114 | /* 1115 | * Retrieve positions's net quantity. 1116 | */ 1117 | function getPositionNetQuantity(pseudoAccount, category, type, 1118 | independentExchange, independentSymbol) { 1119 | return StrToNum(readPositionColumn(pseudoAccount, 1120 | category, type, independentExchange, independentSymbol, 11)); 1121 | } 1122 | 1123 | /* 1124 | * Retrieve positions's buy value. 1125 | */ 1126 | function getPositionBuyValue(pseudoAccount, category, type, 1127 | independentExchange, independentSymbol) { 1128 | return StrToNum(readPositionColumn(pseudoAccount, 1129 | category, type, independentExchange, independentSymbol, 12)); 1130 | } 1131 | 1132 | /* 1133 | * Retrieve positions's sell value. 1134 | */ 1135 | function getPositionSellValue(pseudoAccount, category, type, 1136 | independentExchange, independentSymbol) { 1137 | return StrToNum(readPositionColumn(pseudoAccount, 1138 | category, type, independentExchange, independentSymbol, 13)); 1139 | } 1140 | 1141 | /* 1142 | * Retrieve positions's net value. 1143 | */ 1144 | function getPositionNetValue(pseudoAccount, category, type, 1145 | independentExchange, independentSymbol) { 1146 | return StrToNum(readPositionColumn(pseudoAccount, 1147 | category, type, independentExchange, independentSymbol, 14)); 1148 | } 1149 | 1150 | /* 1151 | * Retrieve positions's buy average price. 1152 | */ 1153 | function getPositionBuyAvgPrice(pseudoAccount, category, type, 1154 | independentExchange, independentSymbol) { 1155 | return StrToNum(readPositionColumn(pseudoAccount, 1156 | category, type, independentExchange, independentSymbol, 15)); 1157 | } 1158 | 1159 | /* 1160 | * Retrieve positions's sell average price. 1161 | */ 1162 | function getPositionSellAvgPrice(pseudoAccount, category, type, 1163 | independentExchange, independentSymbol) { 1164 | return StrToNum(readPositionColumn(pseudoAccount, 1165 | category, type, independentExchange, independentSymbol, 16)); 1166 | } 1167 | 1168 | /* 1169 | * Retrieve positions's realised pnl. 1170 | */ 1171 | function getPositionRealisedPnl(pseudoAccount, category, type, 1172 | independentExchange, independentSymbol) { 1173 | return StrToNum(readPositionColumn(pseudoAccount, 1174 | category, type, independentExchange, independentSymbol, 17)); 1175 | } 1176 | 1177 | /* 1178 | * Retrieve positions's unrealised pnl. 1179 | */ 1180 | function getPositionUnrealisedPnl(pseudoAccount, category, type, 1181 | independentExchange, independentSymbol) { 1182 | return StrToNum(readPositionColumn(pseudoAccount, 1183 | category, type, independentExchange, independentSymbol, 18)); 1184 | } 1185 | 1186 | /* 1187 | * Retrieve positions's overnight quantity. 1188 | */ 1189 | function getPositionOvernightQuantity(pseudoAccount, category, type, 1190 | independentExchange, independentSymbol) { 1191 | return StrToNum(readPositionColumn(pseudoAccount, 1192 | category, type, independentExchange, independentSymbol, 19)); 1193 | } 1194 | 1195 | /* 1196 | * Retrieve positions's multiplier. 1197 | */ 1198 | function getPositionMultiplier(pseudoAccount, category, type, 1199 | independentExchange, independentSymbol) { 1200 | return StrToNum(readPositionColumn(pseudoAccount, 1201 | category, type, independentExchange, independentSymbol, 20)); 1202 | } 1203 | 1204 | /* 1205 | * Retrieve positions's LTP. 1206 | */ 1207 | function getPositionLtp(pseudoAccount, category, type, 1208 | independentExchange, independentSymbol) { 1209 | return StrToNum(readPositionColumn(pseudoAccount, 1210 | category, type, independentExchange, independentSymbol, 21)); 1211 | } 1212 | 1213 | /* 1214 | * Retrieve positions's (platform specific) exchange. 1215 | */ 1216 | function getPositionExchange(pseudoAccount, category, type, 1217 | independentExchange, independentSymbol) { 1218 | return readPositionColumn(pseudoAccount, 1219 | category, type, independentExchange, independentSymbol, 22); 1220 | } 1221 | 1222 | /* 1223 | * Retrieve positions's (platform specific) symbol. 1224 | */ 1225 | function getPositionSymbol(pseudoAccount, category, type, 1226 | independentExchange, independentSymbol) { 1227 | return readPositionColumn(pseudoAccount, 1228 | category, type, independentExchange, independentSymbol, 23); 1229 | } 1230 | 1231 | /* 1232 | * Retrieve positions's date (DD-MM-YYYY). 1233 | */ 1234 | function getPositionDay(pseudoAccount, category, type, 1235 | independentExchange, independentSymbol) { 1236 | return readPositionColumn(pseudoAccount, 1237 | category, type, independentExchange, independentSymbol, 24); 1238 | } 1239 | 1240 | /* 1241 | * Retrieve positions's trading platform. 1242 | */ 1243 | function getPositionPlatform(pseudoAccount, category, type, 1244 | independentExchange, independentSymbol) { 1245 | return readPositionColumn(pseudoAccount, 1246 | category, type, independentExchange, independentSymbol, 25); 1247 | } 1248 | 1249 | /* 1250 | * Retrieve positions's account id as received from trading platform. 1251 | */ 1252 | function getPositionAccountId(pseudoAccount, category, type, 1253 | independentExchange, independentSymbol) { 1254 | return readPositionColumn(pseudoAccount, 1255 | category, type, independentExchange, independentSymbol, 26); 1256 | } 1257 | 1258 | /* 1259 | * Retrieve positions's stock broker. 1260 | */ 1261 | function getPositionStockBroker(pseudoAccount, category, type, 1262 | independentExchange, independentSymbol) { 1263 | return readPositionColumn(pseudoAccount, 1264 | category, type, independentExchange, independentSymbol, 28); 1265 | } 1266 | 1267 | /* 1268 | * Retrieve positions's state (OPEN, CLOSED). 1269 | */ 1270 | function getPositionState(pseudoAccount, category, type, 1271 | independentExchange, independentSymbol) { 1272 | return readPositionColumn(pseudoAccount, 1273 | category, type, independentExchange, independentSymbol, 29); 1274 | } 1275 | 1276 | /* 1277 | * Retrieve positions's direction (LONG, SHORT, NEUTRAL). 1278 | */ 1279 | function getPositionDirection(pseudoAccount, category, type, 1280 | independentExchange, independentSymbol) { 1281 | return readPositionColumn(pseudoAccount, 1282 | category, type, independentExchange, independentSymbol, 30); 1283 | } 1284 | 1285 | /*****************************************************************************/ 1286 | /************************ POSITION DETAIL FUNCTIONS - END ***********************/ 1287 | /*****************************************************************************/ 1288 | 1289 | 1290 | /*****************************************************************************/ 1291 | /************************ MARGIN DETAIL FUNCTIONS - START ***********************/ 1292 | /*****************************************************************************/ 1293 | 1294 | /* 1295 | * Reads margins file and returns a column value for the given margin category. 1296 | */ 1297 | function readMarginColumn(pseudoAccount, category, columnIndex) { 1298 | filePath = getPortfolioMarginsFile(pseudoAccount); 1299 | return fileReadCsvColumnByRowId( filePath, category, 3, columnIndex ); 1300 | } 1301 | 1302 | /* 1303 | * Retrieve margin funds. 1304 | */ 1305 | function getMarginFunds(pseudoAccount, category) { 1306 | return StrToNum(readMarginColumn(pseudoAccount, category, 4)); 1307 | } 1308 | 1309 | /* 1310 | * Retrieve margin utilized. 1311 | */ 1312 | function getMarginUtilized(pseudoAccount, category) { 1313 | return StrToNum(readMarginColumn(pseudoAccount, category, 5)); 1314 | } 1315 | 1316 | /* 1317 | * Retrieve margin available. 1318 | */ 1319 | function getMarginAvailable(pseudoAccount, category) { 1320 | return StrToNum(readMarginColumn(pseudoAccount, category, 6)); 1321 | } 1322 | 1323 | /* 1324 | * Retrieve margin funds for equity category. 1325 | */ 1326 | function getMarginFundsEquity(pseudoAccount) { 1327 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_EQUITY, 4)); 1328 | } 1329 | 1330 | /* 1331 | * Retrieve margin utilized for equity category. 1332 | */ 1333 | function getMarginUtilizedEquity(pseudoAccount) { 1334 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_EQUITY, 5)); 1335 | } 1336 | 1337 | /* 1338 | * Retrieve margin available for equity category. 1339 | */ 1340 | function getMarginAvailableEquity(pseudoAccount) { 1341 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_EQUITY, 6)); 1342 | } 1343 | 1344 | /* 1345 | * Retrieve margin funds for commodity category. 1346 | */ 1347 | function getMarginFundsCommodity(pseudoAccount) { 1348 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_COMMODITY, 4)); 1349 | } 1350 | 1351 | /* 1352 | * Retrieve margin utilized for commodity category. 1353 | */ 1354 | function getMarginUtilizedCommodity(pseudoAccount) { 1355 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_COMMODITY, 5)); 1356 | } 1357 | 1358 | /* 1359 | * Retrieve margin available for commodity category. 1360 | */ 1361 | function getMarginAvailableCommodity(pseudoAccount) { 1362 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_COMMODITY, 6)); 1363 | } 1364 | 1365 | /* 1366 | * Retrieve margin funds for entire account. 1367 | */ 1368 | function getMarginFundsAll(pseudoAccount) { 1369 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_ALL, 4)); 1370 | } 1371 | 1372 | /* 1373 | * Retrieve margin utilized for entire account. 1374 | */ 1375 | function getMarginUtilizedAll(pseudoAccount) { 1376 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_ALL, 5)); 1377 | } 1378 | 1379 | /* 1380 | * Retrieve margin available for entire account. 1381 | */ 1382 | function getMarginAvailableAll(pseudoAccount) { 1383 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_ALL, 6)); 1384 | } 1385 | 1386 | /* 1387 | * Retrieve margin total for equity category. 1388 | */ 1389 | function getMarginTotalEquity(pseudoAccount) { 1390 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_EQUITY, 9)); 1391 | } 1392 | 1393 | /* 1394 | * Retrieve margin total for commodity category. 1395 | */ 1396 | function getMarginTotalCommodity(pseudoAccount) { 1397 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_COMMODITY, 9)); 1398 | } 1399 | 1400 | /* 1401 | * Retrieve margin total for entire account. 1402 | */ 1403 | function getMarginTotalAll(pseudoAccount) { 1404 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_ALL, 9)); 1405 | } 1406 | 1407 | /* 1408 | * Retrieve margin net for equity category. 1409 | */ 1410 | function getMarginNetEquity(pseudoAccount) { 1411 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_EQUITY, 10)); 1412 | } 1413 | 1414 | /* 1415 | * Retrieve margin net for commodity category. 1416 | */ 1417 | function getMarginNetCommodity(pseudoAccount) { 1418 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_COMMODITY, 10)); 1419 | } 1420 | 1421 | /* 1422 | * Retrieve margin net for entire account. 1423 | */ 1424 | function getMarginNetAll(pseudoAccount) { 1425 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_ALL, 10)); 1426 | } 1427 | 1428 | /* 1429 | * Retrieve margin span for equity category. 1430 | */ 1431 | function getMarginSpanEquity(pseudoAccount) { 1432 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_EQUITY, 11)); 1433 | } 1434 | 1435 | /* 1436 | * Retrieve margin span for commodity category. 1437 | */ 1438 | function getMarginSpanCommodity(pseudoAccount) { 1439 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_COMMODITY, 11)); 1440 | } 1441 | 1442 | /* 1443 | * Retrieve margin span for entire account. 1444 | */ 1445 | function getMarginSpanAll(pseudoAccount) { 1446 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_ALL, 11)); 1447 | } 1448 | 1449 | /* 1450 | * Retrieve margin exposure for equity category. 1451 | */ 1452 | function getMarginExposureEquity(pseudoAccount) { 1453 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_EQUITY, 12)); 1454 | } 1455 | 1456 | /* 1457 | * Retrieve margin exposure for commodity category. 1458 | */ 1459 | function getMarginExposureCommodity(pseudoAccount) { 1460 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_COMMODITY, 12)); 1461 | } 1462 | 1463 | /* 1464 | * Retrieve margin exposure for entire account. 1465 | */ 1466 | function getMarginExposureAll(pseudoAccount) { 1467 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_ALL, 12)); 1468 | } 1469 | 1470 | /* 1471 | * Retrieve margin collateral for equity category. 1472 | */ 1473 | function getMarginCollateralEquity(pseudoAccount) { 1474 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_EQUITY, 13)); 1475 | } 1476 | 1477 | /* 1478 | * Retrieve margin collateral for commodity category. 1479 | */ 1480 | function getMarginCollateralCommodity(pseudoAccount) { 1481 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_COMMODITY, 13)); 1482 | } 1483 | 1484 | /* 1485 | * Retrieve margin collateral for entire account. 1486 | */ 1487 | function getMarginCollateralAll(pseudoAccount) { 1488 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_ALL, 13)); 1489 | } 1490 | 1491 | /* 1492 | * Retrieve margin payin for equity category. 1493 | */ 1494 | function getMarginPayinEquity(pseudoAccount) { 1495 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_EQUITY, 14)); 1496 | } 1497 | 1498 | /* 1499 | * Retrieve margin payin for commodity category. 1500 | */ 1501 | function getMarginPayinCommodity(pseudoAccount) { 1502 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_COMMODITY, 14)); 1503 | } 1504 | 1505 | /* 1506 | * Retrieve margin payin for entire account. 1507 | */ 1508 | function getMarginPayinAll(pseudoAccount) { 1509 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_ALL, 14)); 1510 | } 1511 | 1512 | /* 1513 | * Retrieve margin payout for equity category. 1514 | */ 1515 | function getMarginPayoutEquity(pseudoAccount) { 1516 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_EQUITY, 15)); 1517 | } 1518 | 1519 | /* 1520 | * Retrieve margin payout for commodity category. 1521 | */ 1522 | function getMarginPayoutCommodity(pseudoAccount) { 1523 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_COMMODITY, 15)); 1524 | } 1525 | 1526 | /* 1527 | * Retrieve margin payout for entire account. 1528 | */ 1529 | function getMarginPayoutAll(pseudoAccount) { 1530 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_ALL, 15)); 1531 | } 1532 | 1533 | /* 1534 | * Retrieve margin adhoc for equity category. 1535 | */ 1536 | function getMarginAdhocEquity(pseudoAccount) { 1537 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_EQUITY, 16)); 1538 | } 1539 | 1540 | /* 1541 | * Retrieve margin adhoc for commodity category. 1542 | */ 1543 | function getMarginAdhocCommodity(pseudoAccount) { 1544 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_COMMODITY, 16)); 1545 | } 1546 | 1547 | /* 1548 | * Retrieve margin adhoc for entire account. 1549 | */ 1550 | function getMarginAdhocAll(pseudoAccount) { 1551 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_ALL, 16)); 1552 | } 1553 | 1554 | /* 1555 | * Retrieve margin realised mtm for equity category. 1556 | */ 1557 | function getMarginRealisedMtmEquity(pseudoAccount) { 1558 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_EQUITY, 17)); 1559 | } 1560 | 1561 | /* 1562 | * Retrieve margin realised mtm for commodity category. 1563 | */ 1564 | function getMarginRealisedMtmCommodity(pseudoAccount) { 1565 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_COMMODITY, 17)); 1566 | } 1567 | 1568 | /* 1569 | * Retrieve margin realised mtm for entire account. 1570 | */ 1571 | function getMarginRealisedMtmAll(pseudoAccount) { 1572 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_ALL, 17)); 1573 | } 1574 | 1575 | /* 1576 | * Retrieve margin unrealised mtm for equity category. 1577 | */ 1578 | function getMarginUnrealisedMtmEquity(pseudoAccount) { 1579 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_EQUITY, 18)); 1580 | } 1581 | 1582 | /* 1583 | * Retrieve margin unrealised mtm for commodity category. 1584 | */ 1585 | function getMarginUnrealisedMtmCommodity(pseudoAccount) { 1586 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_COMMODITY, 18)); 1587 | } 1588 | 1589 | /* 1590 | * Retrieve margin unrealised mtm for entire account. 1591 | */ 1592 | function getMarginUnrealisedMtmAll(pseudoAccount) { 1593 | return StrToNum(readMarginColumn(pseudoAccount, AT_MARGIN_ALL, 18)); 1594 | } 1595 | 1596 | /*****************************************************************************/ 1597 | /************************ MARGIN DETAIL FUNCTIONS - END ***********************/ 1598 | /*****************************************************************************/ 1599 | 1600 | 1601 | /*****************************************************************************/ 1602 | /************************ HOLDING DETAIL FUNCTIONS - START ***********************/ 1603 | /*****************************************************************************/ 1604 | 1605 | /* 1606 | * Reads holding file and returns a column value for the given symbol. 1607 | */ 1608 | function readHoldingColumn(pseudoAccount, symbol, columnIndex) { 1609 | filePath = getPortfolioHoldingsFile(pseudoAccount); 1610 | return fileReadCsvColumnByRowId( filePath, symbol, 5, columnIndex ); 1611 | } 1612 | 1613 | /* 1614 | * Retrieve holding exchange. 1615 | */ 1616 | function getHoldingExchange(pseudoAccount, symbol) { 1617 | return readHoldingColumn(pseudoAccount, symbol, 4); 1618 | } 1619 | 1620 | /* 1621 | * Retrieve holding ISIN. 1622 | */ 1623 | function getHoldingIsin(pseudoAccount, symbol) { 1624 | return readHoldingColumn(pseudoAccount, symbol, 6); 1625 | } 1626 | 1627 | /* 1628 | * Retrieve holding quantity. 1629 | */ 1630 | function getHoldingQuantity(pseudoAccount, symbol) { 1631 | return StrToNum(readHoldingColumn(pseudoAccount, symbol, 7)); 1632 | } 1633 | 1634 | /* 1635 | * Retrieve holding T1 quantity. 1636 | */ 1637 | function getHoldingT1Quantity(pseudoAccount, symbol) { 1638 | return StrToNum(readHoldingColumn(pseudoAccount, symbol, 8)); 1639 | } 1640 | 1641 | /* 1642 | * Retrieve holding PNL. 1643 | */ 1644 | function getHoldingPnl(pseudoAccount, symbol) { 1645 | return StrToNum(readHoldingColumn(pseudoAccount, symbol, 9)); 1646 | } 1647 | 1648 | /* 1649 | * Retrieve holding product. 1650 | */ 1651 | function getHoldingProduct(pseudoAccount, symbol) { 1652 | return readHoldingColumn(pseudoAccount, symbol, 10); 1653 | } 1654 | 1655 | /* 1656 | * Retrieve holding collateral type. 1657 | */ 1658 | function getHoldingCollateralType(pseudoAccount, symbol) { 1659 | return readHoldingColumn(pseudoAccount, symbol, 11); 1660 | } 1661 | 1662 | /* 1663 | * Retrieve holding collateral quantity. 1664 | */ 1665 | function getHoldingCollateralQuantity(pseudoAccount, symbol) { 1666 | return StrToNum(readHoldingColumn(pseudoAccount, symbol, 12)); 1667 | } 1668 | 1669 | /* 1670 | * Retrieve holding haircut. 1671 | */ 1672 | function getHoldingHaircut(pseudoAccount, symbol) { 1673 | return StrToNum(readHoldingColumn(pseudoAccount, symbol, 13)); 1674 | } 1675 | 1676 | /* 1677 | * Retrieve holding average price. 1678 | */ 1679 | function getHoldingAvgPrice(pseudoAccount, symbol) { 1680 | return StrToNum(readHoldingColumn(pseudoAccount, symbol, 14)); 1681 | } 1682 | 1683 | /* 1684 | * Retrieve holding instrument token. 1685 | */ 1686 | function getHoldingInstToken(pseudoAccount, symbol) { 1687 | return readHoldingColumn(pseudoAccount, symbol, 15); 1688 | } 1689 | 1690 | /* 1691 | * Retrieve holding symbol LTP. 1692 | */ 1693 | function getHoldingLtp(pseudoAccount, symbol) { 1694 | return readHoldingColumn(pseudoAccount, symbol, 21); 1695 | } 1696 | 1697 | /* 1698 | * Retrieve holding current value. 1699 | */ 1700 | function getHoldingCurrentValue(pseudoAccount, symbol) { 1701 | return readHoldingColumn(pseudoAccount, symbol, 22); 1702 | } 1703 | 1704 | /*****************************************************************************/ 1705 | /************************ HOLDING DETAIL FUNCTIONS - END ***********************/ 1706 | /*****************************************************************************/ 1707 | 1708 | 1709 | /*****************************************************************************/ 1710 | /********************* PORTFOLIO SUMMARY FUNCTIONS - START ********************/ 1711 | /*****************************************************************************/ 1712 | 1713 | /* 1714 | * Reads summary file and returns a column value. 1715 | */ 1716 | function readSummaryColumn(pseudoAccount, columnIndex) { 1717 | filePath = getPortfolioSummaryFile(pseudoAccount); 1718 | return fileReadCsvColumn( filePath, 1, columnIndex ); 1719 | } 1720 | 1721 | /* 1722 | * Retrieve portfolio M2M (Position category = DAY). 1723 | */ 1724 | function getPortfolioMtm(pseudoAccount) { 1725 | return StrToNum(readSummaryColumn(pseudoAccount, 2)); 1726 | } 1727 | 1728 | /* 1729 | * Retrieve portfolio PNL (Position category = DAY). 1730 | */ 1731 | function getPortfolioPnl(pseudoAccount) { 1732 | return StrToNum(readSummaryColumn(pseudoAccount, 3)); 1733 | } 1734 | 1735 | /* 1736 | * Retrieve portfolio position count (Position category = DAY). 1737 | */ 1738 | function getPortfolioPositionCount(pseudoAccount) { 1739 | return StrToNum(readSummaryColumn(pseudoAccount, 4)); 1740 | } 1741 | 1742 | /* 1743 | * Retrieve portfolio OPEN position count (Position category = DAY). 1744 | */ 1745 | function getPortfolioOpenPositionCount(pseudoAccount) { 1746 | return StrToNum(readSummaryColumn(pseudoAccount, 5)); 1747 | } 1748 | 1749 | /* 1750 | * Retrieve portfolio CLOSED position count (Position category = DAY). 1751 | */ 1752 | function getPortfolioClosedPositionCount(pseudoAccount) { 1753 | return StrToNum(readSummaryColumn(pseudoAccount, 6)); 1754 | } 1755 | 1756 | /* 1757 | * Retrieve portfolio open short quantity (Position category = DAY). 1758 | */ 1759 | function getPortfolioOpenShortQuantity(pseudoAccount) { 1760 | return StrToNum(readSummaryColumn(pseudoAccount, 7)); 1761 | } 1762 | 1763 | /* 1764 | * Retrieve portfolio open long quantity (Position category = DAY). 1765 | */ 1766 | function getPortfolioOpenLongQuantity(pseudoAccount) { 1767 | return StrToNum(readSummaryColumn(pseudoAccount, 8)); 1768 | } 1769 | 1770 | /* 1771 | * Retrieve portfolio order count. 1772 | */ 1773 | function getPortfolioOrderCount(pseudoAccount) { 1774 | return StrToNum(readSummaryColumn(pseudoAccount, 9)); 1775 | } 1776 | 1777 | /* 1778 | * Retrieve portfolio "open" order count. 1779 | */ 1780 | function getPortfolioOpenOrderCount(pseudoAccount) { 1781 | return StrToNum(readSummaryColumn(pseudoAccount, 10)); 1782 | } 1783 | 1784 | /* 1785 | * Retrieve portfolio "complete" order count. 1786 | */ 1787 | function getPortfolioCompleteOrderCount(pseudoAccount) { 1788 | return StrToNum(readSummaryColumn(pseudoAccount, 11)); 1789 | } 1790 | 1791 | /* 1792 | * Retrieve portfolio "cancelled" order count. 1793 | */ 1794 | function getPortfolioCancelledOrderCount(pseudoAccount) { 1795 | return StrToNum(readSummaryColumn(pseudoAccount, 12)); 1796 | } 1797 | 1798 | /* 1799 | * Retrieve portfolio "rejected" order count. 1800 | */ 1801 | function getPortfolioRejectedOrderCount(pseudoAccount) { 1802 | return StrToNum(readSummaryColumn(pseudoAccount, 13)); 1803 | } 1804 | 1805 | /* 1806 | * Retrieve portfolio "trigger pending" order count. 1807 | */ 1808 | function getPortfolioTriggerPendingOrderCount(pseudoAccount) { 1809 | return StrToNum(readSummaryColumn(pseudoAccount, 14)); 1810 | } 1811 | 1812 | /* 1813 | * Retrieve portfolio M2M (Position category = NET). 1814 | */ 1815 | function getPortfolioMtmNET(pseudoAccount) { 1816 | return StrToNum(readSummaryColumn(pseudoAccount, 15)); 1817 | } 1818 | 1819 | /* 1820 | * Retrieve portfolio PNL (Position category = NET). 1821 | */ 1822 | function getPortfolioPnlNET(pseudoAccount) { 1823 | return StrToNum(readSummaryColumn(pseudoAccount, 16)); 1824 | } 1825 | 1826 | /* 1827 | * Retrieve portfolio position count (Position category = NET). 1828 | */ 1829 | function getPortfolioPositionCountNET(pseudoAccount) { 1830 | return StrToNum(readSummaryColumn(pseudoAccount, 17)); 1831 | } 1832 | 1833 | /* 1834 | * Retrieve portfolio OPEN position count (Position category = NET). 1835 | */ 1836 | function getPortfolioOpenPositionCountNET(pseudoAccount) { 1837 | return StrToNum(readSummaryColumn(pseudoAccount, 18)); 1838 | } 1839 | 1840 | /* 1841 | * Retrieve portfolio CLOSED position count (Position category = NET). 1842 | */ 1843 | function getPortfolioClosedPositionCountNET(pseudoAccount) { 1844 | return StrToNum(readSummaryColumn(pseudoAccount, 19)); 1845 | } 1846 | 1847 | /* 1848 | * Retrieve portfolio open short quantity (Position category = NET). 1849 | */ 1850 | function getPortfolioOpenShortQuantityNET(pseudoAccount) { 1851 | return StrToNum(readSummaryColumn(pseudoAccount, 20)); 1852 | } 1853 | 1854 | /* 1855 | * Retrieve portfolio open long quantity (Position category = NET). 1856 | */ 1857 | function getPortfolioOpenLongQuantityNET(pseudoAccount) { 1858 | return StrToNum(readSummaryColumn(pseudoAccount, 21)); 1859 | } 1860 | 1861 | /*****************************************************************************/ 1862 | /********************** PORTFOLIO SUMMARY FUNCTIONS - END *********************/ 1863 | /*****************************************************************************/ -------------------------------------------------------------------------------- /Formulas/Include/autotrader-button.afl: -------------------------------------------------------------------------------- 1 | _SECTION_BEGIN("AutoTrader Buttons"); 2 | 3 | // Account names parameter 4 | AT_ACCOUNTS = ParamStr("Accounts (comma separated)", "ACC1,ACC2,ACC3"); 5 | 6 | CellHeight = Param("Cell Height",30,5,200,1); 7 | CellWidth = Param("Cell Width",150,5,200,1); 8 | PanelYoffset = Param("Cell Row Offset (px)",30,0,Status("pxheight"),1); 9 | PanelXoffset = Param("Cell Column Offset (px)",20,0,Status("pxwidth"),1); 10 | FontRatio = Param("Font: CellHeight ratio",3,1,20,0.1); 11 | 12 | _SECTION_END(); 13 | 14 | 15 | procedure kStaticVarSet( SName, SValue ) { 16 | ChartID = GetChartID(); 17 | InIndicator = Status("Action") == 1; 18 | if( InIndicator ) StaticVarSet(Sname+ChartID, Svalue); 19 | } 20 | 21 | function kStaticVarGet( SName ) { 22 | ChartID = GetChartID(); 23 | Var = StaticVarGet(Sname+ChartID); 24 | return Var; 25 | } 26 | 27 | procedure kStaticVarSetText( SName, SValue ) { 28 | ChartID = GetChartID(); 29 | InIndicator = Status("Action") == 1; 30 | if( InIndicator ) StaticVarSetText(Sname+ChartID, Svalue); 31 | } 32 | 33 | function kStaticVarGetText( SName ) { 34 | ChartID = GetChartID(); 35 | return StaticVarGetText(Sname+ChartID); 36 | } 37 | 38 | function Column_Begin( ColName ) { 39 | global FontRatio, ColName, ColNumber, CellHeight, CellWidth, PanelXoffset, PanelYoffset; 40 | 41 | ColNumber = VarGet("ColNumber"); 42 | if( IsEmpty( ColNumber ) ) { 43 | VarSet("ColNumber",1); 44 | StaticVarSet("ClickCoordinates",0); 45 | } 46 | else VarSet("ColNumber", ++ColNumber); 47 | 48 | ColName = ColName+GetChartID(); 49 | 50 | GfxSetOverlayMode( 0 ); 51 | GfxSelectFont( "Tahoma", CellHeight/FontRatio, 800 ); 52 | GfxSelectPen( colorBlack ); 53 | GfxSetBkMode( 1 ); 54 | 55 | kStaticVarSet("RowNumber"+ColName, 0); 56 | VarSetText("ColName",ColName); 57 | 58 | return ColNumber; 59 | } 60 | 61 | function Column_End( ) { 62 | global CellHeight, CellWidth, PanelYoffset, PanelXoffset, ColNumber, RowNumber; 63 | 64 | ChartIDStr = NumToStr(GetChartID(),1.0,False); 65 | ColName = VarGetText("ColName"); 66 | ULCellX = PanelXoffset + (ColNumber-1) * CellWidth; 67 | LRCellX = ULCellX + CellWidth; 68 | 69 | for( Row = 1; Row <= RowNumber; Row++ ) { 70 | ULCellY = (Row-1) * CellHeight + PanelYoffset; 71 | LRCellY = ULCellY + CellHeight; 72 | TextCell = kStaticVarGetText("TextCell"+ColName+Row); 73 | TextColor = Nz(kStaticVarGet("TextColor"+ColName+Row)); 74 | BackColor = Nz(kStaticVarGet("BackColor"+ColName+Row)); 75 | GfxSelectSolidBrush( BackColor); 76 | GfxRectangle( ULCellX, ULCellY, LRCellX, LRCellY ); 77 | GfxSetBkColor( BackColor); 78 | GfxSetTextColor( TextColor ); 79 | GfxDrawText( TextCell, ULCellX, ULCellY, LRCellX, LRCellY, 32 | 1 | 4); 80 | } 81 | } 82 | 83 | function TextCell( TextCell, backColor, TextColor) { 84 | global ColNumber, RowNumber; 85 | 86 | ColName = VarGetText("ColName"); 87 | RowNumber = Nz(kStaticVarGet("RowNumber"+ColName))+1; 88 | 89 | kStaticVarSet("RowNumber"+ColName, RowNumber); 90 | kStaticVarSetText("TextCell"+ColName+RowNumber, TextCell); 91 | kStaticVarSet("TextColor"+ColName+RowNumber, TextColor); 92 | kStaticVarSet("BackColor"+ColName+RowNumber, backColor); 93 | } 94 | 95 | function NewColumn() { 96 | VarSet("ColNumber", 0); 97 | } 98 | 99 | function CheckMouseClick( ColNumber, RowNumber ) { 100 | global PanelYoffset, PanelXoffset, CellHeight, CellWidth; 101 | 102 | LButtonDown = GetCursorMouseButtons() == 9; 103 | Click = 0; 104 | 105 | if( LButtonDown ) { 106 | ULCellX = PanelXoffset + (ColNumber-1) * CellWidth; 107 | LRCellX = ULCellX + CellWidth; 108 | ULCellY = (RowNumber -1) * CellHeight + PanelYoffset; 109 | LRCellY = ULCellY + CellHeight; 110 | MouseCoord = Nz(StaticVarGet("ClickCoordinates")); 111 | if( MouseCoord == 0 AND LButtonDown ) 112 | { 113 | MousePx = GetCursorXPosition( 1 ); 114 | MousePy = GetCursorYPosition( 1 ); 115 | if( MousePx > ULCellX AND MousePx < LRCellX AND MousePy > ULCellY AND MousePy < LRCellY ) 116 | { 117 | StaticVarSet("ClickCoordinates",ColNumber*100+RowNumber); 118 | Click = 1; 119 | } 120 | } 121 | } 122 | 123 | return Click; 124 | 125 | } 126 | 127 | function TriggerCell( Label, backColor1, BackColor2, TextColor) { 128 | global ColNumber, RowNumber; 129 | 130 | ColName = VarGetText("ColName"); 131 | RowNumber = Nz(kStaticVarGet("RowNumber"+ColName))+1; 132 | 133 | kStaticVarSet("RowNumber"+ColName, RowNumber); 134 | 135 | Trigger = CheckMouseClick( ColNumber, RowNumber ); 136 | 137 | if( Trigger ) BackColor = backColor2; else BackColor = backColor1; 138 | 139 | kStaticVarSetText("TextCell"+ColName+RowNumber, Label); 140 | kStaticVarSet("TextColor"+ColName+RowNumber, TextColor); 141 | kStaticVarSet("BackColor"+ColName+RowNumber, backColor); 142 | 143 | return Trigger; 144 | } -------------------------------------------------------------------------------- /Formulas/Include/autotrader-defaults.afl: -------------------------------------------------------------------------------- 1 | /************************************************ 2 | * Contains default value functions. 3 | * 4 | * Author: Stocks Developer 5 | ************************************************/ 6 | 7 | 8 | /*********************** CONSTANTS - START ***********************/ 9 | 10 | AT_COMMA = ","; 11 | AT_PIPE = "|"; 12 | AT_BLANK = ""; 13 | AT_NA = "NA"; 14 | 15 | AT_VARIETY_REGULAR = "REGULAR"; 16 | AT_VARIETY_BO = "BO"; 17 | AT_VARIETY_CO = "CO"; 18 | 19 | AT_PRODUCT_INTRADAY = "INTRADAY"; 20 | AT_PRODUCT_DELIVERY = "DELIVERY"; 21 | AT_PRODUCT_NORMAL = "NORMAL"; 22 | 23 | AT_POSITION_MIS = "MIS"; 24 | AT_POSITION_CNC = "CNC"; 25 | AT_POSITION_NRML = "NRML"; 26 | AT_POSITION_BO = "BO"; 27 | AT_POSITION_CO = "CO"; 28 | 29 | AT_ORDER_LIMIT = "LIMIT"; 30 | AT_ORDER_MARKET = "MARKET"; 31 | AT_ORDER_STOP_LOSS = "STOP_LOSS"; 32 | AT_ORDER_SL_MARKET = "SL_MARKET"; 33 | 34 | AT_PLACE_ORDER_CMD = "PLACE_ORDER"; 35 | AT_CANCEL_ORDER_CMD = "CANCEL_ORDER"; 36 | AT_CANCEL_ALL_ORDERS_CMD = "CANCEL_ALL_ORDERS"; 37 | AT_MODIFY_ORDER_CMD = "MODIFY_ORDER"; 38 | AT_CANCEL_CHILD_ORDER_CMD = "CANCEL_CHILD_ORDER"; 39 | AT_SQUARE_OFF_POSITION = "SQUARE_OFF_POSITION"; 40 | AT_SQUARE_OFF_PORTFOLIO = "SQUARE_OFF_PORTFOLIO"; 41 | 42 | AT_MARGIN_EQUITY = "EQUITY"; 43 | AT_MARGIN_COMMODITY = "COMMODITY"; 44 | AT_MARGIN_ALL = "ALL"; 45 | 46 | /*********************** CONSTANTS - END ***********************/ 47 | 48 | function defaultProductType() { 49 | return AT_PRODUCT_INTRADAY; 50 | } 51 | 52 | function defaultAmo() { 53 | return False; 54 | } 55 | 56 | function defaultValidity() { 57 | return "DAY"; 58 | } 59 | 60 | function defaultDisclosedQuantity() { 61 | return 0; 62 | } 63 | 64 | function defaultTriggerPrice() { 65 | return 0; 66 | } 67 | 68 | function defaultTarget() { 69 | return 0; 70 | } 71 | 72 | function defaultStoploss() { 73 | return 0; 74 | } 75 | 76 | function defaultTrailingStoploss() { 77 | return 0; 78 | } 79 | 80 | function defaultStrategyId() { 81 | return -1; 82 | } 83 | 84 | function defaultComments() { 85 | return AT_BLANK; 86 | } 87 | 88 | function defaultVariety() { 89 | return AT_VARIETY_REGULAR; 90 | } 91 | -------------------------------------------------------------------------------- /Formulas/Include/autotrader-ipc.afl: -------------------------------------------------------------------------------- 1 | /************************************************ 2 | * Contains inter process communication details. 3 | * 4 | * Author: Stocks Developer 5 | ************************************************/ 6 | 7 | /* Windows separator */ 8 | WIN_SEPARATOR = "\\"; 9 | 10 | /* Linux/unix separator */ 11 | UNIX_SEPARATOR = "/"; 12 | 13 | /* Inter process communication directory */ 14 | /* This directory should be same as the one set on at-desktop client */ 15 | IPC_DIR = ""; 16 | 17 | /* Directory that contains input files for AutoTrader */ 18 | INPUT_DIR = IPC_DIR + WIN_SEPARATOR + "input"; 19 | 20 | /* Directory that contains output files from AutoTrader */ 21 | OUTPUT_DIR = IPC_DIR + WIN_SEPARATOR + "output"; 22 | 23 | /* AutoTrader commands */ 24 | COMMANDS_FILE = INPUT_DIR + WIN_SEPARATOR + "commands.csv"; 25 | 26 | /* Portfolio orders */ 27 | function getPortfolioOrdersFile(pseudoAccount) { 28 | return OUTPUT_DIR + WIN_SEPARATOR + pseudoAccount + "-orders.csv"; 29 | } 30 | 31 | /* Portfolio positions */ 32 | function getPortfolioPositionsFile(pseudoAccount) { 33 | return OUTPUT_DIR + WIN_SEPARATOR + pseudoAccount + "-positions.csv"; 34 | } 35 | 36 | /* Portfolio margins */ 37 | function getPortfolioMarginsFile(pseudoAccount) { 38 | return OUTPUT_DIR + WIN_SEPARATOR + pseudoAccount + "-margins.csv"; 39 | } 40 | 41 | /* Portfolio holdings */ 42 | function getPortfolioHoldingsFile(pseudoAccount) { 43 | return OUTPUT_DIR + WIN_SEPARATOR + pseudoAccount + "-holdings.csv"; 44 | } 45 | 46 | /* Portfolio summary */ 47 | function getPortfolioSummaryFile(pseudoAccount) { 48 | return OUTPUT_DIR + WIN_SEPARATOR + pseudoAccount + "-summary.csv"; 49 | } -------------------------------------------------------------------------------- /Formulas/Include/autotrader-next-bar.afl: -------------------------------------------------------------------------------- 1 | /************************************************ 2 | * Helper functions to place order on next Bar or Candle. 3 | * 4 | * Author: Stocks Developer 5 | ************************************************/ 6 | 7 | _SECTION_BEGIN("Next-Bar"); 8 | 9 | // Keep it ON to avoid short lived signals (which come and disapper). 10 | // Some signals arrive when the bar or candle is being built, 11 | // but disapper by the time bar or candle it complete. 12 | // In such cases, user will NOT see a signal on the bar but orders will be placed, 13 | // because orders would normally be sent as soon as a signal comes. 14 | // Setting this flag ON avoids this problem, as the system will wait for 15 | // the next bar or candle to place an order. 16 | AT_PLACE_ORDER_ON_NEXT_BAR = ParamToggle("Place order on next bar", "OFF|ON"); 17 | 18 | AT_PREVIOUS_BAR_END_TIME = "AT_PREVIOUS_BAR_END_TIME"; 19 | 20 | function isNewBar() { 21 | result = True; 22 | 23 | if(AT_PLACE_ORDER_ON_NEXT_BAR) { 24 | prevEndTime = readStaticVariable(AT_ACCOUNT, AT_PREVIOUS_BAR_END_TIME); 25 | currEndTime = Status( "lastbarend" ); 26 | result = (prevEndTime > 0 && prevEndTime != currEndTime); 27 | } 28 | 29 | return result; 30 | } 31 | 32 | _SECTION_END(); -------------------------------------------------------------------------------- /Formulas/Include/autotrader-post-util.afl: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * 3 | * AutoTrader utility functions library functions that uses AutoTrader API. 4 | * DO NOT MODIFY THIS FILE 5 | * Version: 1.0 6 | * 7 | ******************************************************************************/ 8 | 9 | /* 10 | * Returns True if the order is the first of the day for the current chart. 11 | */ 12 | function isFirstOrder(account, symbol) { 13 | lastTradeType = readLastOrderTradeType(account, symbol); 14 | return lastTradeType == ""; 15 | } 16 | 17 | /* 18 | * We double the quantity if order is not first, so that we can square off earlier position 19 | * and enter into a new position. 20 | */ 21 | function calcDoubleQuantity(account, symbol, defaultQuantity) { 22 | qty = defaultQuantity; 23 | if(isFirstOrder(account, symbol) == False) { 24 | qty = defaultQuantity * 2; 25 | } 26 | return qty; 27 | } 28 | 29 | /* 30 | * Calculates position type. 31 | */ 32 | function calcPositionType(variety, productType) { 33 | positionType = ""; 34 | 35 | switch(variety) { 36 | case AT_VARIETY_REGULAR: 37 | switch(productType) { 38 | case AT_PRODUCT_INTRADAY: 39 | positionType = AT_POSITION_MIS; 40 | break; 41 | 42 | case AT_PRODUCT_DELIVERY: 43 | positionType = AT_POSITION_CNC; 44 | break; 45 | 46 | case AT_PRODUCT_NORMAL: 47 | positionType = AT_POSITION_NRML; 48 | break; 49 | 50 | default: 51 | _TRACE("ERROR: Invalid Product Type passed, cannot calculate position type. Product type [" + productType + "]"); 52 | break; 53 | } 54 | break; 55 | 56 | case AT_VARIETY_CO: 57 | positionType = AT_POSITION_CO; 58 | break; 59 | 60 | case AT_VARIETY_BO: 61 | positionType = AT_POSITION_BO; 62 | break; 63 | 64 | default: 65 | _TRACE("ERROR: Invalid variety passed, cannot calculate position type. Variety [" + variety + "]"); 66 | break; 67 | } 68 | 69 | return positionType; 70 | } -------------------------------------------------------------------------------- /Formulas/Include/autotrader-pre-util.afl: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * 3 | * AutoTrader utility functions library functions that do not depende on AutoTrader API. 4 | * DO NOT MODIFY THIS FILE 5 | * Version: 1.0 6 | * 7 | ******************************************************************************/ 8 | 9 | /** 10 | * Stores numeric data in a static variable. Account is used to create a unique key. 11 | */ 12 | procedure saveStaticVariable(account, key, value) 13 | { 14 | amiStaticVarSet(account + key, value); 15 | } 16 | 17 | /** 18 | * Reads numeric data from a static variable. Account is used to create a unique key. 19 | */ 20 | function readStaticVariable(account, key) 21 | { 22 | return amiStaticVarGet(account + key); 23 | } 24 | 25 | /** 26 | * Stores text data in a static variable. Account is used to create a unique key. 27 | */ 28 | procedure saveStaticVariableText(account, key, value) 29 | { 30 | amiStaticVarSetText(account + key, value); 31 | } 32 | 33 | /** 34 | * Reads text data from a static variable. Account is used to create a unique key. 35 | */ 36 | function readStaticVariableText(account, key) 37 | { 38 | return amiStaticVarGetText(account + key); 39 | } 40 | -------------------------------------------------------------------------------- /Formulas/Include/autotrader-quantity-mapping.afl: -------------------------------------------------------------------------------- 1 | /************************************************ 2 | * Helps to use different quantity per symbol in scanner. 3 | * 4 | * Author: Stocks Developer 5 | ************************************************/ 6 | 7 | _SECTION_BEGIN("Quantity-Mapping"); 8 | 9 | // A flag to indicate whether quantity must be loaded from a quantity file 10 | // This allows you to use different quantity per scanner symbol 11 | AT_USE_QUANTITY_MAPPING = ParamToggle("Use quantity mapping file", "OFF|ON", 0); 12 | AT_QUANTITY_MAPPING_FILE = ParamStr("Quantity maping file", "C:\\quantity-mapping.csv"); 13 | 14 | /* 15 | * Looks for a quantity in the mapping file. 16 | * Allows you to map different quantity for each scanner symbol. 17 | * On error, it will return quantity set in chart parameters. 18 | */ 19 | function getQuantity(datafeedSymbol) { 20 | quantity = AT_QUANTITY; 21 | 22 | if(AT_USE_QUANTITY_MAPPING) { 23 | fileQuantity = fileReadCsvColumnByRowId(AT_QUANTITY_MAPPING_FILE, datafeedSymbol, 1, 2); 24 | if(fileQuantity == "") { 25 | _TRACE("Could not find quantity for [" + datafeedSymbol + "]."); 26 | _TRACE("Please make sure following line exists in the file [" + AT_QUANTITY_MAPPING_FILE + "]."); 27 | _TRACE(datafeedSymbol + ","); 28 | } else { 29 | quantity = StrToNum(fileQuantity); 30 | } 31 | } 32 | 33 | return quantity; 34 | } 35 | 36 | _SECTION_END(); -------------------------------------------------------------------------------- /Formulas/Include/autotrader-square-off.afl: -------------------------------------------------------------------------------- 1 | /************************************************ 2 | * Functions that help with square-off. 3 | * 4 | * Author: Stocks Developer 5 | ************************************************/ 6 | 7 | _SECTION_BEGIN("Square-off"); 8 | 9 | // Square off parameters 10 | AT_SQUARE_OFF_FLAG = ParamToggle("Intraday Auto Square-off", "OFF|ON", 0); 11 | AT_SQUARE_OFF_TIME = ParamTime( "Intraday Square-off Time", "15:00:00"); 12 | AT_SQUARE_OFF_STATUS_KEY = "SQUARE_OFF_STATUS"; 13 | 14 | function isSquareOffRequestSent() { 15 | soffStatus = readStaticVariable(AT_ACCOUNT, AT_SQUARE_OFF_STATUS_KEY); 16 | return soffStatus > 0; 17 | } 18 | 19 | function isSquareOffRequestSentForAcc(account) { 20 | soffStatus = readStaticVariable(account, AT_SQUARE_OFF_STATUS_KEY); 21 | return soffStatus > 0; 22 | } 23 | 24 | function shouldSquareOff() { 25 | return ((AT_SQUARE_OFF_FLAG == 1) AND (Now(4) > AT_SQUARE_OFF_TIME)); 26 | } 27 | 28 | _SECTION_END(); 29 | -------------------------------------------------------------------------------- /Formulas/Include/autotrader-symbol-mapping.afl: -------------------------------------------------------------------------------- 1 | /************************************************ 2 | * Helps to map datafeed symbols to AutoTrader symbols. 3 | * 4 | * Author: Stocks Developer 5 | ************************************************/ 6 | 7 | 8 | _SECTION_BEGIN("Symbol-Mapping"); 9 | 10 | // A flag to indicate whether symbols must be loaded from a mapping file 11 | AT_USE_SYMBOL_MAPPING = ParamToggle("Use symbol mapping file", "OFF|ON", 0); 12 | AT_SYMBOL_MAPPING_FILE = ParamStr("Symbol maping file", "C:\\symbol-mapping.csv"); 13 | 14 | /* 15 | * Looks for a AutoTrader Web's symbol in the mapping file. 16 | * Allows you to map datafeed provider's symbols to AutoTrader Web's symbols. 17 | * On error, it will return same symbol that was passed to it. 18 | */ 19 | function getSymbol(datafeedSymbol) { 20 | atWebSymbol = datafeedSymbol; 21 | 22 | if(AT_USE_SYMBOL_MAPPING) { 23 | fileSymbol = fileReadCsvColumnByRowId(AT_SYMBOL_MAPPING_FILE, datafeedSymbol, 1, 2); 24 | if(fileSymbol == "") { 25 | _TRACE("Could not find AutoTrader Web's symbol for [" + datafeedSymbol + "]."); 26 | _TRACE("Please make sure following line exists in the file [" + AT_SYMBOL_MAPPING_FILE + "]."); 27 | _TRACE(datafeedSymbol + ","); 28 | } else { 29 | atWebSymbol = fileSymbol; 30 | } 31 | } 32 | 33 | return atWebSymbol; 34 | } 35 | 36 | _SECTION_END(); -------------------------------------------------------------------------------- /Formulas/Include/autotrader.afl: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * 3 | * AutoTrader API library. 4 | * DO NOT MODIFY THIS FILE 5 | * Version: 1.0 6 | * 7 | ******************************************************************************/ 8 | 9 | /* Import public amibroker libraries */ 10 | 11 | #include_once 12 | #include_once 13 | #include_once 14 | #include_once 15 | #include_once 16 | 17 | /* Import AutoTrader specific amibroker libraries */ 18 | 19 | #include_once 20 | #include_once 21 | #include_once 22 | #include_once 23 | #include_once -------------------------------------------------------------------------------- /Formulas/Include/conversion-util.afl: -------------------------------------------------------------------------------- 1 | /************************************************ 2 | * Utility functions data conversion. 3 | * 4 | * Author: Stocks Developer 5 | ************************************************/ 6 | 7 | AT_TIMEZONE_IST = 19800; 8 | 9 | /** 10 | * Converts a number to a string without any decimal places. 11 | */ 12 | function convertIntegerToString(number) { 13 | return NumToStr(number, 1.0, False); 14 | } 15 | 16 | /* 17 | * Converts a given datetime object into milliseconds since epoch. 18 | */ 19 | function convertDateTimeToMillisSinceEpoch(dt) { 20 | epoch = StrToDateTime("1970-01-01 00:00:00"); 21 | return DateTimeDiff( dt, epoch ); 22 | } 23 | 24 | /* 25 | * Converts a given milliseconds since epoch into datetime object. 26 | */ 27 | function convertMillisToDateTimeSinceEpoch(millis) { 28 | epoch = StrToDateTime("1970-01-01 00:00:00"); 29 | amount = millis / 1000; 30 | amount += AT_TIMEZONE_IST; 31 | return DateTimeAdd( epoch, amount, in1Second ); 32 | } -------------------------------------------------------------------------------- /Formulas/Include/file-util.afl: -------------------------------------------------------------------------------- 1 | /************************************************ 2 | * Utility functions for working with files. 3 | * 4 | * Wiki: https://github.com/Pritesh-Mhatre/amibroker-library/wiki/File-Functions 5 | * 6 | * Author: Stocks Developer 7 | ************************************************/ 8 | 9 | /** 10 | * Version check. 11 | */ 12 | Version(5.8); 13 | 14 | /** 15 | * Default variables. 16 | */ 17 | 18 | FILE_DEFAULT_WRITE_MODE = "a"; 19 | 20 | FILE_DEFAULT_READ_MODE = "r"; 21 | 22 | FILE_DEFAULT_WRITE_SHARED_FLAG = True; 23 | 24 | FILE_DEFAULT_WRITE_RETRY_COUNT = 50; 25 | 26 | FILE_DEFAULT_MAX_LINES_SAFETY_CHECK = 100000; 27 | 28 | /** 29 | * Amibroker function to write a given line along with newline character. Returns True on successful write. 30 | * 31 | * Documentation: https://github.com/Pritesh-Mhatre/amibroker-library/wiki/File-Functions#fileWriteLineAdvanced 32 | */ 33 | function fileWriteLineAdvanced( filePath, mode, shared, retryCount, line ) 34 | { 35 | 36 | result = True; 37 | 38 | for( i = 1; i <= retryCount; i++ ) { 39 | fh = fopen(filePath, mode, shared); 40 | if (fh) { 41 | fputs( line + "\n", fh ); 42 | fclose( fh ); 43 | break; 44 | } else { 45 | result = False; 46 | _TRACE("[Attempt: " + i + "] Failed to write line: " + line); 47 | } 48 | } 49 | 50 | return result; 51 | } 52 | 53 | /** 54 | * Amibroker function to write a given line along with newline character. Returns True on successful write. 55 | * 56 | * Documentation: https://github.com/Pritesh-Mhatre/amibroker-library/wiki/File-Functions#fileWriteLine 57 | */ 58 | function fileWriteLine( filePath, line ) 59 | { 60 | return fileWriteLineAdvanced( filePath, FILE_DEFAULT_WRITE_MODE, FILE_DEFAULT_WRITE_SHARED_FLAG, FILE_DEFAULT_WRITE_RETRY_COUNT, line); 61 | } 62 | 63 | /** 64 | * Amibroker function to read column value from a CSV file by given row number. 65 | * Returns column value if found otherwise blank. 66 | * 67 | * Documentation: https://github.com/Pritesh-Mhatre/amibroker-library/wiki/File-Functions#fileReadCsvColumn 68 | */ 69 | function fileReadCsvColumn( filePath, rowIndex, columnIndex ) { 70 | fh = fopen( filePath, FILE_DEFAULT_READ_MODE ); 71 | result = ""; 72 | 73 | if( fh ) 74 | { 75 | for( i = 1; ! feof( fh ) AND i < FILE_DEFAULT_MAX_LINES_SAFETY_CHECK; i++ ) 76 | { 77 | // read a line of text 78 | line = fgets( fh ); 79 | 80 | if( i < rowIndex ) 81 | { 82 | continue; 83 | } 84 | 85 | result = StrExtract( line, columnIndex - 1 ); 86 | break; 87 | } 88 | 89 | fclose( fh ); 90 | } 91 | else 92 | { 93 | _TRACE("ERROR: file can not be found " + filePath); 94 | } 95 | 96 | return result; 97 | } 98 | 99 | /** 100 | * Amibroker function to read column value from a CSV file by identifying row by the given rowId. 101 | * Returns column value if found otherwise blank. 102 | * 103 | * Documentation: https://github.com/Pritesh-Mhatre/amibroker-library/wiki/File-Functions#fileReadCsvColumnByRowId 104 | */ 105 | function fileReadCsvColumnByRowId( filePath, rowId, rowIdColumnIndex, columnIndex ) { 106 | fh = fopen( filePath, FILE_DEFAULT_READ_MODE ); 107 | result = ""; 108 | 109 | if( fh ) 110 | { 111 | for( i = 0; ! feof( fh ) AND i < FILE_DEFAULT_MAX_LINES_SAFETY_CHECK; i++ ) 112 | { 113 | // read a line of text 114 | line = fgets( fh ); 115 | 116 | if( line == "" ) 117 | { 118 | // Continue if we encounter a blank line 119 | continue; 120 | } 121 | 122 | if(rowId == StrExtract( line, rowIdColumnIndex - 1 )) { 123 | result = StrExtract( line, columnIndex - 1 ); 124 | break; 125 | } 126 | } 127 | 128 | fclose( fh ); 129 | } 130 | else 131 | { 132 | _TRACE("ERROR: file can not be found " + filePath); 133 | } 134 | 135 | return result; 136 | } -------------------------------------------------------------------------------- /Formulas/Include/logs-util.afl: -------------------------------------------------------------------------------- 1 | /************************************************ 2 | * A logging library which writes logs to files. 3 | * 4 | * Wiki: https://github.com/Pritesh-Mhatre/amibroker-library/wiki/Logging-Functions 5 | * 6 | * Author: Stocks Developer 7 | ************************************************/ 8 | 9 | #include_once 10 | #include_once 11 | #include_once 12 | 13 | _SECTION_BEGIN("Logs"); 14 | 15 | LOGS_DEFAULT_WRITE_RETRY_COUNT = 2; 16 | 17 | /* Trace is used for detailed logging */ 18 | LOG_TRACE = "TRACE"; 19 | 20 | /* Debug is used for logging that helps with debugging */ 21 | LOG_DEBUG = "DEBUG"; 22 | 23 | /* Info is used for normal informative logs */ 24 | LOG_INFO = "INFO"; 25 | 26 | /* Error is used to log errors */ 27 | LOG_ERROR = "ERROR"; 28 | 29 | /* To indicate whether log directory was created or not */ 30 | LOGS_DIRECTORY_CHECK = "LOGS_DIRECTORY_CHECK"; 31 | 32 | /* To indicate whether errors were observed in logging */ 33 | LOGS_ERRORS_FOUND = "LOGS_ERRORS_FOUND"; 34 | 35 | /* AmiBroker Home */ 36 | // Note this will differ from one system to another. 37 | // As of AmiBroker version 6.0, there is no way to get the installation directory. 38 | AMIBROKER_HOME = "C:\\Program Files\\AmiBroker"; 39 | 40 | /* Default logs directory */ 41 | LOGS_DIRECTORY_DEFAULT = AMIBROKER_HOME + "\\" + "Logs"; 42 | 43 | // A flag to indicate whether quantity must be loaded from a quantity file 44 | // This allows you to use different quantity per scanner symbol 45 | LOGS_SWITCH = ParamToggle("Enable logs", "OFF|ON", 1); 46 | 47 | // Make sure AmiBroker has read & write permission to this directory 48 | LOGS_DIRECTORY = ParamStr("Log files directory", LOGS_DIRECTORY_DEFAULT); 49 | 50 | // Log file name 51 | LOGS_FILE_NAME = ParamStr("Log file name", Name()); 52 | 53 | // Log file extension 54 | LOGS_FILE_EXTENSION = ParamList("Log file extension", "csv|txt|log"); 55 | 56 | // Log file column separator 57 | LOGS_FILE_COLUMN_SEPARATOR = ParamStr("Log file column separator", ","); 58 | 59 | // A flag to indicate whether quantity must be loaded from a quantity file 60 | // This allows you to use different quantity per scanner symbol 61 | LOGS_SCANNER_MODE = ParamToggle("Using in scanner or analysis window", "OFF|ON", 0); 62 | 63 | /** 64 | * Logs the given text to the file. 65 | */ 66 | function logInternal(category, logText) { 67 | 68 | if(LOGS_SWITCH AND amiStaticVarGet(LOGS_ERRORS_FOUND) == False) { 69 | 70 | // Make directory 71 | if(amiStaticVarGet(LOGS_DIRECTORY_CHECK) == False) { 72 | 73 | // Sometimes AmiBroker installation path is different to the default path, 74 | // hence this check is needed 75 | if(strStartsWith(LOGS_DIRECTORY, AMIBROKER_HOME)) { 76 | _TRACE("Making sure that AmiBroker Home exists: " + AMIBROKER_HOME); 77 | fmkdir(AMIBROKER_HOME); 78 | } 79 | 80 | _TRACE("Creating logs directory: " + LOGS_DIRECTORY); 81 | fmkdir(LOGS_DIRECTORY); 82 | amiStaticVarSet(LOGS_DIRECTORY_CHECK, True); 83 | } 84 | 85 | // File Name 86 | fileName = LOGS_FILE_NAME; 87 | if(LOGS_SCANNER_MODE) { 88 | fileName = Name(); 89 | } 90 | 91 | // File path 92 | filePath = LOGS_DIRECTORY + "\\" + fileName + "_" 93 | + Now(6) + "-" + Now(7) + "-"+ Now(8) 94 | + "." + LOGS_FILE_EXTENSION; 95 | 96 | // Line 97 | line = Now() + LOGS_FILE_COLUMN_SEPARATOR + category + LOGS_FILE_COLUMN_SEPARATOR + logText; 98 | 99 | // log to the file 100 | result = fileWriteLineAdvanced( filePath, FILE_DEFAULT_WRITE_MODE, 101 | FILE_DEFAULT_WRITE_SHARED_FLAG, LOGS_DEFAULT_WRITE_RETRY_COUNT, line); 102 | 103 | if(result == False) { 104 | _TRACE("ERROR: Could not write logs to: " + filePath); 105 | _TRACE("Please do ONE of the following changes:"); 106 | _TRACE("1. Please change the logs path OR"); 107 | _TRACE("2. Make sure current path exists and AmiBroker has write permission to it. [" + LOGS_DIRECTORY + "]"); 108 | _TRACE("Logging has been disabled due to previous errors."); 109 | 110 | amiStaticVarSet(LOGS_ERRORS_FOUND, True); 111 | } 112 | } 113 | } 114 | 115 | /** 116 | * Logs a TRACE category statement. 117 | * 118 | * Documentation: https://github.com/Pritesh-Mhatre/amibroker-library/wiki/Logging-Functions#logtrace 119 | */ 120 | function logTrace(logText) { 121 | logInternal(LOG_TRACE, logText); 122 | } 123 | 124 | /** 125 | * Logs a DEBUG category statement. 126 | * 127 | * Documentation: https://github.com/Pritesh-Mhatre/amibroker-library/wiki/Logging-Functions#logdebug 128 | */ 129 | function logDebug(logText) { 130 | logInternal(LOG_DEBUG, logText); 131 | } 132 | 133 | /** 134 | * Logs a INFO category statement. 135 | * 136 | * Documentation: https://github.com/Pritesh-Mhatre/amibroker-library/wiki/Logging-Functions#loginfo 137 | */ 138 | function logInfo(logText) { 139 | logInternal(LOG_INFO, logText); 140 | } 141 | 142 | /** 143 | * Logs a ERROR category statement. 144 | * 145 | * Documentation: https://github.com/Pritesh-Mhatre/amibroker-library/wiki/Logging-Functions#logerror 146 | */ 147 | function logError(logText) { 148 | logInternal(LOG_ERROR, logText); 149 | } 150 | 151 | _SECTION_END(); -------------------------------------------------------------------------------- /Formulas/Include/misc-util.afl: -------------------------------------------------------------------------------- 1 | /************************************************ 2 | * Miscellaneous utility functions 3 | * 4 | * Wiki: https://github.com/Pritesh-Mhatre/amibroker-library/wiki/Miscellaneous-Functions 5 | * 6 | * Author: Stocks Developer 7 | ************************************************/ 8 | 9 | /* 10 | * Functions for static variables which are unique accross symbols and charts. 11 | */ 12 | global amiStaticVarKey; 13 | 14 | /* 15 | * Use symbol name and chart id to keep static variable unique. 16 | */ 17 | amiStaticVarKey = Name() + NumToStr(GetChartID(), 1.0, False); 18 | 19 | /** 20 | * Stores numeric value in static variable by preparing a unique chart specific key. 21 | * 22 | * Documentation: https://github.com/Pritesh-Mhatre/amibroker-library/wiki/Miscellaneous-Functions#amiStaticVarSet 23 | */ 24 | procedure amiStaticVarSet(key, value) 25 | { 26 | global amiStaticVarKey; 27 | StaticVarSet(key + amiStaticVarKey, value); 28 | } 29 | 30 | /** 31 | * Retrieves numeric data stored in static variable using a unique chart specific key. 32 | * 33 | * Documentation: https://github.com/Pritesh-Mhatre/amibroker-library/wiki/Miscellaneous-Functions#amiStaticVarGet 34 | */ 35 | function amiStaticVarGet(key) 36 | { 37 | global amiStaticVarKey; 38 | if(IsNull(var = StaticVarGet(key + amiStaticVarKey) ) ) { 39 | var = 0; 40 | } 41 | return var; 42 | } 43 | 44 | /** 45 | * Stores text value in static variables by preparing a unique chart specific key. 46 | * 47 | * Documentation: https://github.com/Pritesh-Mhatre/amibroker-library/wiki/Miscellaneous-Functions#amiStaticVarSetText 48 | */ 49 | procedure amiStaticVarSetText(key, value ) 50 | { 51 | global amiStaticVarKey; 52 | StaticVarSetText(key + amiStaticVarKey, value); 53 | } 54 | 55 | /** 56 | * Retrieves numeric data stored in static variable using a unique chart specific key. 57 | * 58 | * Documentation: https://github.com/Pritesh-Mhatre/amibroker-library/wiki/Miscellaneous-Functions#amiStaticVarGetText 59 | */ 60 | function amiStaticVarGetText(key ) 61 | { 62 | global amiStaticVarKey; 63 | return StaticVarGetText(key + amiStaticVarKey); 64 | } 65 | 66 | /* 67 | * Reverses trade type, return BUY for SELL an vice versa. 68 | */ 69 | function reverseTradeType(tradeType) { 70 | result = ""; 71 | 72 | if(tradeType == "SELL") { 73 | result = "BUY"; 74 | } 75 | if(tradeType == "BUY") { 76 | result = "SELL"; 77 | } 78 | if(tradeType == "SHORT") { 79 | result = "COVER"; 80 | } 81 | if(tradeType == "COVER") { 82 | result = "SHORT"; 83 | } 84 | 85 | return result; 86 | } 87 | 88 | function tryEnterCriticalSection(secname) 89 | { 90 | global _cursec; 91 | _cursec= ""; 92 | 93 | // try obtaining semaphore for 1000 ms 94 | for( i = 0; i < 1000; i++ ) 95 | if( StaticVarCompareExchange( secname, 1, 0 ) == 0 ) 96 | { 97 | _cursec = secname; 98 | break; 99 | } 100 | else ThreadSleep( 1 ); //sleep one millisecond 101 | 102 | return _cursec != ""; 103 | } 104 | 105 | // call it ONLY when tryEnterCriticalSection returned TRUE ! 106 | function leaveCriticalSection() 107 | { 108 | global _cursec; 109 | if( _cursec != "" ) 110 | { 111 | StaticVarSet( _cursec, 0 ); 112 | _cursec = ""; 113 | } 114 | } -------------------------------------------------------------------------------- /Formulas/Include/text-util.afl: -------------------------------------------------------------------------------- 1 | /************************************************ 2 | * Utility functions that work on text data. 3 | * 4 | * Wiki: https://github.com/Pritesh-Mhatre/amibroker-library/wiki/Text-Functions 5 | * 6 | * Author: Stocks Developer 7 | ************************************************/ 8 | 9 | /** 10 | * AmiBroker substring function. Returns a string that is a substring of the string. 11 | * Implementation of Java substring function in AmiBroker. 12 | * 13 | * Documentation: https://github.com/Pritesh-Mhatre/amibroker-library/wiki/Text-Functions#strSubstring 14 | */ 15 | function strSubstring(text, beginIndex, endIndex) { 16 | 17 | result = ""; 18 | length = strlen(text); 19 | 20 | // Perform validation 21 | if(beginIndex < 0 OR endIndex > length OR beginIndex > endIndex) { 22 | _TRACE("Function: strSubstring, Error: Validation failure for string: " + text); 23 | result = ""; 24 | } else { 25 | // Calculate the result 26 | count = endIndex - beginIndex; 27 | result = StrMid(text, beginIndex, count); 28 | } 29 | 30 | return result; 31 | } 32 | 33 | /** 34 | * Amibroker function that returns first N characters of a string. 35 | * 36 | * Documentation: https://github.com/Pritesh-Mhatre/amibroker-library/wiki/Text-Functions#strFirstN 37 | */ 38 | function strFirstN(text, n) { 39 | 40 | result = ""; 41 | 42 | // Perform validation 43 | if(n < 0) { 44 | _TRACE("Function: strFirstN, Error: Validation failure for string: " + text); 45 | result = ""; 46 | } else { 47 | // Calculate the result 48 | result = StrMid(text, 0, n); 49 | } 50 | 51 | return result; 52 | } 53 | 54 | 55 | /** 56 | * Amibroker function that returns last N characters of a string. 57 | * 58 | * Documentation: https://github.com/Pritesh-Mhatre/amibroker-library/wiki/Text-Functions#strLastN 59 | */ 60 | function strLastN(text, n) { 61 | 62 | result = ""; 63 | length = strlen(text); 64 | 65 | // Perform validation 66 | if(n < 0 OR n > length) { 67 | _TRACE("Function: strLastN, Error: Validation failure for string: " + text); 68 | result = ""; 69 | } else { 70 | // Calculate the result 71 | start = length - n; 72 | result = StrMid(text, start, n); 73 | } 74 | 75 | return result; 76 | } 77 | 78 | /** 79 | * Amibroker function to find whether two strings are equal (case-sensitive). 80 | * 81 | * Documentation: https://github.com/Pritesh-Mhatre/amibroker-library/wiki/Text-Functions#strEquals 82 | */ 83 | function strEquals(a, b) { 84 | return (a == b); 85 | } 86 | 87 | /** 88 | * Amibroker function to find whether two strings are equal (case-insensitive). 89 | * 90 | * Documentation: https://github.com/Pritesh-Mhatre/amibroker-library/wiki/Text-Functions#strEqualsIgnoreCase 91 | */ 92 | function strEqualsIgnoreCase(a, b) { 93 | aLower = StrToLower(a); 94 | bLower = StrToLower(b); 95 | 96 | return (aLower == bLower); 97 | } 98 | 99 | /** 100 | * Amibroker function to find whether a string starts with specified prefix. 101 | * 102 | * Documentation: https://github.com/Pritesh-Mhatre/amibroker-library/wiki/Text-Functions#strStartsWith 103 | */ 104 | function strStartsWith(text, prefix) { 105 | beginning = strFirstN(text, strlen(prefix)); 106 | 107 | return strEquals(beginning, prefix); 108 | } 109 | 110 | /** 111 | * Amibroker function to find whether a string ends with specified suffix. 112 | * 113 | * Documentation: https://github.com/Pritesh-Mhatre/amibroker-library/wiki/Text-Functions#strEndsWith 114 | */ 115 | function strEndsWith(text, suffix) { 116 | ending = strLastN(text, strlen(suffix)); 117 | 118 | return strEquals(ending, suffix); 119 | } 120 | 121 | /** 122 | * Amibroker function to find whether a string is empty or not. 123 | * It a string contains only whitespaces, then it is considered as an empty string. 124 | * 125 | * Documentation: https://github.com/Pritesh-Mhatre/amibroker-library/wiki/Text-Functions#strIsEmpty 126 | */ 127 | function strIsEmpty(text) { 128 | return (StrTrim(text, "") == ""); 129 | } 130 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AmiBroker library for single or multi-account automated trading on Zerodha, Upstox, AliceBlue, Finvasia, Angel Broking, Fyers, IIFL, 5Paisa, Profitmart, Mastertrust 2 | 3 | ## Introduction 4 | **[AutoTrader Web](https://stocksdeveloper.in/autotrader-web/)** is our next generation automated trading & PMS software suite. **Most preferred tool by portfolio & fund managers, algorithmic traders as well as sub-brokers.** 5 | 6 | It allows you to **trade & manage multiple trading accounts** across **different stock brokers from a single system**. 7 | 8 | You can trade **manually or automate your trading** strategies using our APIs. We provide easy to use **API libraries in AmiBroker, MetaTrader, Excel, Java, Python, C#**. You can also use our APIs from **any other programming languages via HTTP REST or CSV files**. 9 | 10 | Our aim is to provide advanced features to our users, which are mostly available to HNI or wealthy fund managers in their custom built trading systems. 11 | 12 | Massively reduce trading costs based on following features: 13 | - **No need to purchase API subscription** from your stock broker 14 | - Reduced development efforts as you can **change stock broker with just a few clicks** 15 | - **Multi-account trading from a single system**, so you only need one computer and one datafeed 16 | 17 | ## Features 18 | - Trade & manage multiple trading accounts from anywhere via browser on mobile or PC 19 | - Allows your trading strategies to place/modify/cancel orders as well as read live portfolio 20 | - Low latency (less than 200 milliseconds on average for order placements) 21 | - Works across all operating systems (Windows, Mac, Unix, Linux) 22 | - Place bulk orders into one or more trading accounts 23 | - Truly broker independent. Switch your trading account across any broker without making any code change 24 | - System handles broker specific implementation internally 25 | - System also handles broker specific trading symbol formats internally 26 | - Support for well known brokers 27 | - Zerodha 28 | - Upstox 29 | - AliceBlue 30 | - Finvasia 31 | - Fyers 32 | - Angel Broking 33 | - A **[complete list of features](https://stocksdeveloper.in/autotrader-web-features/)** 34 | 35 | ## Help 36 | - **[User Guide](https://stocksdeveloper.in/documentation/index/)** 37 | - **[User Guide - AmiBroker Library](https://stocksdeveloper.in/documentation/client-setup/amibroker-library/)** 38 | - **[User Guide - API Docs](https://stocksdeveloper.in/documentation/api/)** 39 | 40 | # AmiBroker Open Source Utilities 41 | 42 | We have also created a public free to use AmiBroker utilities. They provide easy to use readymade functions for most common tasks. 43 | 44 | These utilities are built to help AmiBroker users by providing many useful functions which are not built-in. AmiBroker is a tool used for analysing stock market data and writing trading strategies. And our focus will be to provide functions that will make AFL coding easy. This library provides feature on top of the built-in features available. We hope that traders find this amibroker library useful for writing their trading strategies. 45 | 46 | Detailed documentation is available at: https://github.com/Pritesh-Mhatre/amibroker-library/wiki 47 | --------------------------------------------------------------------------------