text:
Test if a string is parenthesly balanced
We call a parens group the open paren (, its matching close paren ) and everything inside them.
A parens group or string is called parenthesly balanced if it contains either nothing or only 2 parenthesly balanced parens groups.
For example:
The string   "(()())()"      is parenthesly balanced
              (    )()       Because it contains exactly 2 parenthesly balanced parens groups
               ()()          The left one is parenthesly balanced because it contains 2 parenthesly balanced parens groups (balanced because they are empty). The right one is parenthesly balanced because it contains nothing.

Likewise:
The string   "(()(()))()"    is not parenthesly balanced
              (      )()     Because it contains a parens group that is not parenthesly balanced: the left one
               ()(  )        The left one is not balanced because it contains a parens group that is not balanced: the right one
                  ()         The right one is not balanced because it only contains one balanced group.

So, a parenthesly balanced string or parens group should either:

Contain nothing at all.
Or contain only and exactly 2 parenthesly balanced parens groups. It should contain nothing else.

Task:
Your task is to write a function or program that checks if a given string is a parenthesly balanced one or not.
Input:
Input will be a string or list of characters or something similar. You can assume that the string will only consist of the characters '(' and ')'. You can also assume that each open paren ( will have its matching close paren ), so don't worry about strings like "(((" or ")(" or "(())("...
Note: As mentioned by @DigitalTrauma in his comment bellow, it's ok to subtitute the () combo by other characters (such as <>, [], ...), if it's causing additional work like escaping in some languages
Output:
Anything to signal whether the string is parenthesly balanced or not (true or false, 1 or 0, ...). Please include in your answer what your function/program is expected to yield.
Examples:
""                                        => True
"()()"                                    => True
"()(()())"                                => True
"(()(()(()())))(()())"                    => True
"(((((((()())())())())())())())()"        => True
"()"                                      => False
"()()()"                                  => False
"(())()"                                  => False
"()(()(())())"                            => False
"(()())(((((()())()))())())"              => False
"()(()()()())"                            => False
"()(()(()())()())"                        => False

The last two examples really made a difference!
Best of luck!

Anything to signal whether the string is parenthesly balanced or not Is consistent output required, i.e.  only two values?

@LuisMendo Could be categories. i.e. truthy values to signal truthiness and falsy values to signal otherwise. So there could be more, but it should be consistent nevertheless.

Is it okay if I take a binary list as an input? For instance, "(()())()" would be represented as [0, 0, 1, 0, 1, 1, 0, 1]. This would remove the necessity to convert the input to character code and then subtracting.

Related question: https://codegolf.stackexchange.com/questions/166457/golf-a-parentheses-matching-algorithm

@JungHwanMin I think that will deviates a lot from the puzzle so I think we'll stick with characters like () or [], ...

@WindmillCookies I don't see how that's related to this one. Totally different things. Even the concept is different.

Japt v2, 20 bytes
V="()"V¥iU1 eViV²1 V

Test it online!
Everyone misunderstood the challenge at first and though that each pair of parentheses had to contain an even number of sub-pairs, when in fact the challenge actually asks for 0 or 2 sub-pairs. So here's my revised answer, using the same technique as before.
We can still solve the challenge with recursive replacement. The thing is, instead of just removing all occurrences of ()(), we need to make sure that there's nothing else in the same wrapper besides the ()() (in other words, no ()()()() or anything like that). We can do this by recursively replacing (()()) with ().
The new problem is that the input itself does not have one pair of outer parentheses (as that would make it not a parenthesly balanced string), forcing us to wrap it in an extra pair to fully reduce it. Finally, the end result for balanced strings is now () instead of the empty string, so we check for equality rather than just taking logical NOT of the output.

sed 4.2.2, 30
:
s/(()())/()/
t
/^()()$\|^$/q1

Try it online.
This returns a shell exit code of 1 for True and 0 for False.
:               # label
s/(()())/()/    # replace "(()())" with "()"
t               # jump back to label if above replacement matched
/^()()$\|^$/q1  # exit code 1 if remaining buffer is exactly "()()" or empty
                # otherwise exit with code 0

Perl 5 -lp, 24 22 bytes
$_=/^((<(?1)?>){2})?$/

Try it online! Link includes test cases. Edit: Saved 2 bytes thanks to @JoKing. Explanation: Just a recursive regex. The outer capturing group represents a balanced string as a < followed by an optional balanced string followed by a >, twice. Note that most of the other answers are able to use ()s but this costs an extra two bytes:
$_=/^((\((?1)?\)){2})?$/

Try it online! Link includes test cases.

Since you can use other pairs of brackets, you can save two bytes by using <>

@JoKing Almost all of the other answers were able to use ()s so I didn't think it was a fair comparison, however I see @ngn's APL answer also uses <>s so I've updated this one.

Brachylog, 28 bytes
Ẹ|~c["(",A,")(",B,")"]∧A;B↰ᵐ

Try it online!
Explanation
                                    --  The string perfectly balanced iff
Ẹ                                   --      the string is empty
 |                                  --  or
  ~c["(",A,")(",B,")"]              --      the string can be written id the format of "($A)($B)"
                      ∧             --          where
                       A;B ᵐ        --          both A and B
                          ↰         --          are perfectly balanced

6502 machine code routine, 48 bytes
A0 00 84 FD A2 00 B1 FB F0 0E C8 C9 29 18 F0 06 8A 48 E6 FD 90 EE B0 0A E0 01
90 06 E0 02 38 D0 01 18 A5 FD F0 09 C6 FD 68 AA E8 B0 F5 90 D7 60

Expects a pointer to a string in $fb/$fc which is expected to only contain ( and ). Clears C (Carry) flag if the string is "paranthesely balanced", sets it otherwise (which is a typical idiom on the 6502, set carry "on error"). Does nothing sensible on invalid input.
Although the algorithm is recursive, it doesn't call itself (which would need more bytes and make the code position dependent) but instead maintains a recursion depth itself and uses "simple" branching.
Commented disassembly
; function to determine a string is "paranthesly balanced"
;
; input:
;   $fb/$fc: address of the string
; output:
;   C flag set if not balanced
; clobbers:
;   $fd:     recursion depth
;   A,X,Y

 .isparbal:
A0 00       LDY #$00            ; string index
84 FD       STY $FD             ; and recursion depth
 .isparbal_r:
A2 00       LDX #$00            ; set counter for parantheses pairs
 .next:
B1 FB       LDA ($FB),Y         ; load next character
F0 0E       BEQ .done           ; end of string -> to final checks
C8          INY                 ; increment string index
C9 29       CMP #$29            ; compare with ')'
18          CLC                 ; and reset carry
F0 06       BEQ .cont           ; if ')' do checks and unwind stack
8A          TXA                 ; save counter ...
48          PHA                 ; ... on stack
E6 FD       INC $FD             ; increment recursion depth
90 EE       BCC .isparbal_r     ; and recurse
 .cont:
B0 0A       BCS .unwind         ; on previous error, unwind directly
 .done:
E0 01       CPX #$01            ; less than one parantheses pair
90 06       BCC .unwind         ; -> ok and unwind
E0 02       CPX #$02            ; test for 2 parantheses pairs
38          SEC                 ; set error flag
D0 01       BNE .unwind         ; if not 2 -> is error and unwind
18          CLC                 ; clear error flag
 .unwind:
A5 FD       LDA $FD             ; check recursion depth
F0 09       BEQ .exit           ; 0 -> we're done
C6 FD       DEC $FD             ; otherwise decrement
68          PLA                 ; get "pair counter" ...
AA          TAX                 ; ... from stack
E8          INX                 ; and increment
B0 F5       BCS .unwind         ; continue unwinding on error
90 D7       BCC .next           ; otherwise continue reading string
 .exit:
60          RTS

Example C64 assembler program using the routine:
Online demo

Code in ca65 syntax:
.import isparbal   ; link with routine above

.segment "BHDR" ; BASIC header
                .word   $0801           ; load address
                .word   $080b           ; pointer next BASIC line
                .word   2018            ; line number
                .byte   $9e             ; BASIC token "SYS"
                .byte   "2061",$0,$0,$0 ; 2061 ($080d) and terminating 0 bytes

.bss
linebuf:        .res    256

.data
prompt:         .byte   "> ", $0
truestr:        .byte   "true", $0
falsestr:       .byte   "false", $0

.code
inputloop:
                lda     #<prompt        ; display prompt
                ldy     #>prompt
                jsr     $ab1e

                lda     #<linebuf       ; read string into buffer
                ldy     #>linebuf
                ldx     #0              ; effectively 256
                jsr     readline

                lda     #<linebuf       ; address of string to $fb/fc
                sta     $fb
                lda     #>linebuf
                sta     $fc
                jsr     isparbal        ; call function

                bcs     isfalse
                lda     #<truestr
                ldy     #>truestr
                bne     printresult
isfalse:        lda     #<falsestr
                ldy     #>falsestr
printresult:    jmp     $ab1e           ; output true/false and exit

; read a line of input from keyboard, terminate it with 0
; expects pointer to input buffer in A/Y, buffer length in X
.proc readline
                dex
                stx     $fb
                sta     $fc
                sty     $fd
                ldy     #$0
                sty     $cc             ; enable cursor blinking
                sty     $fe             ; temporary for loop variable
getkey:         jsr     $f142           ; get character from keyboard
                beq     getkey
                sta     $2              ; save to temporary
                and     #$7f
                cmp     #$20            ; check for control character
                bcs     checkout        ; no -> check buffer size
                cmp     #$d             ; was it enter/return?
                beq     prepout         ; -> normal flow
                cmp     #$14            ; was it backspace/delete?
                bne     getkey          ; if not, get next char
                lda     $fe             ; check current index
                beq     getkey          ; zero -> backspace not possible
                bne     prepout         ; skip checking buffer size for bs
checkout:       lda     $fe             ; buffer index
                cmp     $fb             ; check against buffer size
                beq     getkey          ; if it would overflow, loop again
prepout:        sei                     ; no interrupts
                ldy     $d3             ; get current screen column
                lda     ($d1),y         ; and clear
                and     #$7f            ;   cursor in
                sta     ($d1),y         ;   current row
output:         lda     $2              ; load character
                jsr     $e716           ;   and output
                ldx     $cf             ; check cursor phase
                beq     store           ; invisible -> to store
                ldy     $d3             ; get current screen column
                lda     ($d1),y         ; and show
                ora     #$80            ;   cursor in
                sta     ($d1),y         ;   current row
                lda     $2              ; load character
store:          cli                     ; enable interrupts
                cmp     #$14            ; was it backspace/delete?
                beq     backspace       ; to backspace handling code
                cmp     #$d             ; was it enter/return?
                beq     done            ; then we're done.
                ldy     $fe             ; load buffer index
                sta     ($fc),y         ; store character in buffer
                iny                     ; advance buffer index
                sty     $fe
                bne     getkey          ; not zero -> ok
done:           lda     #$0             ; terminate string in buffer with zero
                ldy     $fe             ; get buffer index
                sta     ($fc),y         ; store terminator in buffer
                sei                     ; no interrupts
                ldy     $d3             ; get current screen column
                lda     ($d1),y         ; and clear
                and     #$7f            ;   cursor in
                sta     ($d1),y         ;   current row
                inc     $cc             ; disable cursor blinking
                cli                     ; enable interrupts
                rts                     ; return
backspace:      dec     $fe             ; decrement buffer index
                bcs     getkey          ; and get next key
.endproc

V, 21, 20 bytes
é(Á)òÓ(“()()…)òø^()$

Try it online! or Verify all test cases!
é(                      " Insert '(' at the beginning of the line
  Á)                    " Append ')' at the end
    ò         ò         " Recursively...
     Ó                  "   Remove...
      (                 "     '('
       “    …           "     (Limit the part that is removed to this section of the match)
        ()()            "     '()()'
             )          "     ')'
                        " (effectively, this replaces '(()())' with '()', but it's one byte shorter than the straightforward approach
               ø        " Count...
                ^()$    "   Lines containing exactly '()' and nothing more

Hexdump:
00000000: e928 c129 f2d3 2893 2829 2829 8529 f2f8  .(.)..(.()().)..
00000010: 5e28 2924                                ^()$

Can you explain your code so I can (hopefully) find a testcase that doesn't work, like I did with @Adàm's answer.

@ibrahimmahrir Done.

C (gcc), 113 bytes
p(a,r,e,n)char*a;{if(*a-40)return 1;for(r=1,e=0;e<2;r&=e++||*a==40)for(r*=n=p(++a);n+=*a++-40?~0:1;);r=r&&*a-40;}

Try it online!
Explanation
p(a,r,e,n)char*a;{   // function and variable declaration
 if(*a-40)return 1;  // string does not start with '(', thus is empty
 for(r=1,e=0;e<2;    // r: return value, e: group id (look for exactly two groups)
 r&=e++||*a==40)     // after the first group, a second shall follow
  for(r*=n=p(++a);   // check that the group is itself balanced
  n+=*a++-40?~0:1;); // skip group
 r=r&&*a-40;}        // additionally, after those two groups there shall follow none

Try it online!

Perl 6,  43 41  37 bytes
{my rule f{\([<&f>**2]?\)};?/^<&f>**2$|^$/}

Test it
{(my$f)=/\([<$f>**2]?\)/;?/^[<$f>**2]?$/}

Test it
{$!=/\([<$!>**2]?\)/;?/^[<$!>**2]?$/}

Test it
Expanded:
{  # bare block lambda with implicit parameter $_

  $! = # store regex into $! (no need to declare it)
  /
    \(

      [
        <$!> ** 2 # recurse into regex twice
      ]?          # optionally

    \)
  /;

  ?      # boolify (causes it to be run against $_)

    /
      ^         # beginning of string

      <$!> ** 2 # match using regex twice

      $         # end of string

    |           # or

      ^ $       # empty string
    /
}

JavaScript (ES6), 63 bytes
Takes input as an array of characters. Returns false for parenthesly balanced, true for not parenthesly balanced.
a=>[...a,k=0].some(c=>c<')'?!(a[k]=-~a[k++]):a[k]=~5>>a[k--]&1)

Try it online!
Commented
a =>                     // a[] = input array of characters; we are going to reuse it to
  [                      // store the number of parenthesis groups at each depth
    ...a,                // append all characters
    k = 0                // initialize k = current depth to 0 and append a value that will
  ]                      // be treated as a final closing parenthesis for the root level
  .some(c =>             // for each character c in this array:
    c < ')' ?            //   if c is an opening parenthesis:
      !(                 //     increment the number of groups at the current depth
        a[k] = -~a[k++]  //     increment the depth
      )                  //     yield false
    :                    //   else:
      a[k] = ~5          //     make sure that the current depth contains either 0 or 2
             >> a[k--]   //     groups, by shifting the 1-complement of 5 (101 in binary)
             & 1         //     and testing the least significant bit
                         //     it resets the number of groups to 0 if the bit is not set
                         //     otherwise, it forces some() to return true
                         //     decrement the depth
  )                      // end of some()

Recursive, 54 bytes
Using recursive replacements (like in ETHproductions' Japt answer) is however significantly shorter.
Takes input as a string. Returns 1 for parenthesly balanced, 0 for not parenthesly balanced.
f=s=>s==(s=s.split`(()())`.join`()`)?!s|s=='()()':f(s)

Try it online!

Recursive, 46 bytes
This one throws a recursion error for not parenthesly balanced:
f=s=>!s|s=='()()'||f(s.split`(()())`.join`()`)

Try it online!

I'm not that good in JavaScript but could
x[k]=-~x[k++]
be replaced with
x[k]++;k++
or even
++x[k++]
?

@АндрейЛомакин No, because x[k] is initially undefined and x[k]++ would give NaN, whereas -~undefined gives 1.

@АндрейЛомакин I'm now re-using the input array, so a[k] initially contains a character. But the same logic applies to strings: applying the ++ operator on them yields NaN, but bitwise operators (such as ~) force them to be coerced to 0 beforehand.

Takes javascript to a whole new level. :D

Haskell, 82 59 bytes
all(`elem`[0,2]).foldl(#)[0]
b#'('=0:b
(x:y:z)#_=y+1:z++[x]

Try it online!
I assume it can be golfed much further since it's my first time golfing in haskell, so any tricks or comments are more than welcome.
EDIT - Thanks @nimi for saving 23 bytes (more than 28% of the original submission :)

Some tips: no need for the () around y+1. As unnamed functions are allowed, you can drop the f=, r[0] is a proper function. Put the base case r b[] at the end and switch to a infix function (say #), then you can use b#_=. You can also change your algorithm slightly by building the list to check for 0s and 2s step by step instead of carrying it around the calls of r in an accumulator r(x:y:z) ... = x : r (...) a with base case r b [] = b. Do the check after the initial call r[0]. All in all 73 bytes.

...  Try it online!.

... or even better: stay with the accumulator and switch to foldl (59 bytes): Try it online!.

@nimi Thank you very much, exactly the kind of tips I was looking for :)

MATL, 26 25 bytes
oo~`tnw52B5LZttnb<]XB10X-

Try it online!
Thanks to @ETHProductions' answer for the "replace (()()) with ()" idea, and @JungHwan Min's question comment for the idea of seeing the brackets as binary digits.
Output is an empty array for truthy, a positive number for falsey - which I think is allowed by OP's comment: "Could be categories. i.e. truthy values to signal truthiness and falsy values to signal otherwise." If it's not, we can add n at the end for +1 byte, to have 0 as truthy output and 1 as falsey output.
With comments:
o         % Convert the parantheses to their ASCII codes
          %  40 for '(', 41 for ')'
o         % Parity - 1 for odd, 0 for even
~         % Not - change 0 to 1 and vice versa, so '(' is now 1 and ')' 0
          % Input char array is now a binary array B
`         % Do-while loop
  tn          % Get the length of the array
  w           % Bring the array B back on top
  52B         % Push the binary value of 52 on stack
              %  [1 1 0 1 0 0] (equivalent to '(()())')
  5L          % Push the constant [1 0] for '()'
  Zt          % Replace the sequence [1 1 0 1 0 0] in array B
              %  with [1 0]
  tn          % Get the length of the array after replacement
  b<          % Has it decreased? If so, continue loop
  ]       % end loop
          % Final value for balanced input will be
          %  either [1 0 1 0] for the remaining outer '()()'
          %  or an empty array [] for empty '' input
XB        % Convert the final binary array back to decimal
10X-      % Set difference, remove 10 from that result
          % Result is [] empty array for balanced input, otherwise
          %  some decimal number ≠ 10 for unbalanced input

C# (.NET Core), 78 71 bytes
f=s=>{var r=s.Replace("(()())","()");return r==s?s==""|s=="()()":f(r);}

Try it online!

R, 71 bytes
f=function(s,r=sub('(()())','()',s,f=T))'if'(r==s,s==''|s=='()()',f(r))

Try it online!

porting of recursive Japt solution of @ETHproductions
-2 bytes thanks to @JayCe

Another - longer - solution but interesting for the different approach
R, 85 bytes
g=gsub;!sum(eval(parse(t=g('\\)\\(',')-(',g('\\)','-1)',g('\\(','(2+',scan(,'')))))))

Try it online!
Explanation :
Take the input string and replaces :
'('  with '(2+'
')'  with '-1)'
')(' with ')-('

then evaluates the resulting expression. If it's equal to zero is balanced, otherwise is not. The use of sum is only necessary to handle the empty string case, because its evaluation returns NULL.
e.g.
()(()()) => (2+-1)-(2+(2+-1)-(2+-1)-1) = 0
(()())   => (2+(2+-1)-(2+-1)-1)        = 1

Save two bytes: f=function(s,r=sub('(()())','()',s,f=T))'if'(r==s,s==''|s=='()()',f(r))

You should put the shorter solution first

@ASCII-only: you're right, but since it's basically a porting of another solution it seemed like "stealing" :P

@digEmAll Well, in a lot of challenges here most of the challenges do just port another solution

APL (Dyalog Classic), 27 bytes
3>≢'<<><>>'⎕r'<>'⍣≡1⌽'><',⎕

Try it online!

Wolfram Language (Mathematica), 65 bytes
#=={}||{1,1}==(#//.{a___,"(",i:1...,")",b___}/;1!=+i<3:>{a,1,b})&

Try it online!

05AB1E, 18 16 13 bytes
…(ÿ)…(()∞„()©:®Q

Port of @ETHproductions's Japt answer to fix the test case ()(()()(()())(()())).
-2 bytes thanks to @Adnan.
Based on this comment of OP I now use () as truthy value, and anything else as falsey. If both values need to be consistent instead of just one, it would be the old 16-bytes answer instead (…(ÿ)…(()∞„()©:®Q), returning 0 for truthy and 1 for falsey test cases.
Try it online or verify all test cases.
Explanation
…(ÿ)             # Take the input (implicitly) and surround it with "(" and ")"
            :    # Infinite replacement of:
    …(()∞        #  "(()())"    ("(()" mirrored)
         „()     #  with "()"
                 # After the infinite replacement: return the result
                 # ("()" for truthy; falsey otherwise)

(Old 18-bytes answer which failed for test case ()(()()(()())(()()))..):
ΔD„()∞©6∍å_i®õ.:]Ā

Try it online or verify all test cases.

I think you can use the infinite replace method: „()∞õ:g_.

no wait I misunderstood the challenge

@Adnan I thought so at first as well, but it fails for test cases containing (()()()()) which should return falsey. Every parenthesis group should contain exactly 0 or 2 inner groups.

You can replace '(®')J with …(ÿ).

@Adnan Thanks! I knew ÿ existed, but never used it before, so completely forgot about it.

Prolog, 46 bytes
a-->p,p.
a-->[].
p-->[l],a,[r].
f(X):-a(X,[]).

Try it online! or Verify all test cases!
Uses lists of l and r as input, e.g. "()()" is tested as f([l,r,l,r])..
The first three lines are the grammar of valid strings in Prolog's Definite Clause Grammar syntax. a(A,B). returns true when A is a list which follows the grammar and B is empty. Thus the main function f takes some X and checks whether a(X,[]) holds.

Python 2, 73 71 bytes
f=lambda s,P='(()())':P in s and f(s.replace(P,'()'))or s in['()()','']

Try it online!

Python2, 95 94 bytes
f=lambda i:g(eval("(%s)"%i.replace(")","),")))
g=lambda i:len(i)in(0,2)and all(g(j)for j in i)

Try it online!
f() transforms the string into a nested tuple, which it passes to g().
g() recursively navigates the tuple and returns False if any element doesn't have exactly 0 or 2 children.
Saved one byte by using string formatting.

brainfuck, 50 bytes
,[<+>[-[->>]<[-[--[>->,]]>>]<]<[>>],]<[--[>->]]<+.

Formatted:
,
[
  <+>
  [
    -[->>]
    <
    [
      -
      [
        --
        [
          >->,
        ]
      ]
      >>
    ]
    <
  ]
  <[>>]
  ,
]
<
[
  --
  [
    >->
  ]
]
<+.

Expects a string of ( and ) without a trailing newline, and outputs \x01 for true and \x00 for false. (For legibility, you can e.g. add 48 +s before the final . to make it print 1 and 0 instead.)
Try it online
This maintains a stack with the number of groups at each depth, distinguishing characters by parity and checking whether the number of groups is in {0, 2} after each close parenthesis; if the condition is not met, consumes the rest of the input and sets a flag; then checks the condition again at the end of the program.
If we are allowed to terminate the input stream with an odd character, we can omit the final check <[--[>->]] to save 10 bytes. (If \n weren't inconveniently even, I might have proposed this variant as the main answer.)
(We could also save some bytes by changing the output format to \x00 for true and non-\x00 for false, which seems to be allowed (maybe accidentally) by the problem statement as written, but anyway it wouldn't be very interesting, and I prefer not to make that change.)

Java 10, 99 96 95 83 bytes
s->{s="("+s+")";for(var p="";!p.equals(s);s=s.replace("(()())","()"))p=s;return s;}

Port of my 05AB1E answer (so also returns () as truthy and anything else as falsey).
Try it online.
Explanation:
s->{                 // Method with String as both parameter and return-type
  s="("+s+")";       //  Surround the input-String between "(" and ")"
  for(var p="";      //  Previous-String, starting empty
      !p.equals(s)   //  Loop as long as the previous and current Strings differ
      ;              //    After every iteration:
       s=s.replace("(()())","()"))
                     //     Replace all "(()())" with "()"
    p=s;             //   Set the previous String with the current
  return s;}         //  Return the modified input-String
                     //  (if it's now "()" it's truthy; falsey otherwise)

return s; can be return"()".equals(s); if an actual boolean result was required.

You can save one byte if you just check !s.contains("()()(")

@Charlie Thanks, but the code contained a bug anyway, so had to change it. It's now fixed (for the last added falsey test case), and golfed by 4 bytes at the same time.

Stax, 13 11 bytes
₧aaS▐îî»Å·╢

Run and debug it
I saved two bytes when I realized the inputs can coincidentally be implicitly evalled as array literals.  By removing the double quotes, the input is simplified.
The general idea is to eval the input as an array literal, and recursively map the elements to check parethesly balance.  If the final assertion ever fails, then there will be a subsequent pop on an empty stack.  In stax, popping with empty stacks immediately terminates the program.
Unpacked, ungolfed, and commented, it looks like this.
        input is implicitly treated as array literals
L       wrap entire input stack in an array
G       jump to the trailing '}', and come back when done
}       terminate the program, the rest is a recursive call target
{Gm     map array on top of the stack by using the recursive call target
%       get the length of the mapped array
02\#    is the length one of [0, 2]?
|c      assert value is truthy, pop if not

Run this one

authors: Андрей Ломакин

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
The Clock Hands of Doom
You are chained to a chair. Underneath you is a huge volcano. A 12-hour clock next to you ticks ominously, and you see that it has wires leading from the back up to a chain, which will drop you into the center of the earth. Taped to the clock is a note:

Each clock hand has an electrode. When both clock hands are in the same position, the power flows and you die. That is, unless you can tell me the exact time that this will occur, to the nearest minute.

You have a computer that knows every programming language. You need to create the shortest (this is code-golf, and standard loopholes are prohibited) program you can, and tell the evil scientist what the time will be. Your program should take input (in any method), consisting of the hour and minute. It should return the next hour and minute (in any method) that this occurs.
According to the OEIS page, the eleven overlap times are:
00:00:00 plus 0/11 s, 01:05:27 plus 3/11 s,
02:10:54 plus 6/11 s, 03:16:21 plus 9/11 s,
04:21:49 plus 1/11 s, 05:27:16 plus 4/11 s,
06:32:43 plus 7/11 s, 07:38:10 plus 10/11 s,
08:43:38 plus 2/11 s, 09:49:05 plus 5/11 s,
10:54:32 plus 8/11 s.

The next time would be 12:00:00. The seconds and their fractional parts are not needed for this challenge. Simply round to the nearest minute.
Test cases:
0:00 (Or 12:00) > 1:05
1:00 > 1:05
11:56 > 12:00 (Or 0:00)
6:45 > 7:38
5:00 > 5:27
6:30 > 6:33 (round up)

The program can be a function, or full program. I do not care if you choose 0:00 or 12:00, and both are acceptable. Good luck!

Comments are not for extended discussion; this conversation has been moved to chat.

JavaScript (Node.js), 54 47 bytes (round to the nearest)
-7 bytes. Thanks @user202729
a=>b=>[(a+=b>5.46*a)+a/11|0,a%12*65.46%60+.5|0]

Try it online!

JavaScript (Node.js), 40 33 44 bytes (rounds towards 0)
-3 bytes thanks to @Arnauld
-4 bytes thanks to @Kevin Cruijssen
a=>b=>[(a+=b>5.46*a)+a/11|0,a%12*65.46%60|0]

Explanation
a=>b=>[(a+=b>5.46*a)+a/11|0,a%12*65.46%60|0]    Full Code
a                                               Hours
   b                                            Minutes
    =>[                    ,               ]    return array with
       (a+=        )                            add to the current hour
           b>5.46*a                             1 if the minute's clock hand has
                                                passed the hour's clock hand. Here we use
                                                equation 60*a/11 which is the same as 5.46*a
                    +a/11                       and add 1 when hour is 11
                         |0                     floor the result

                            a%12*65.46%60|0     Here we do equation ((720/11)*a) (mod 60)
                            a%12                In case of hour 12 we take 0
                                *65.46          multiply hour by 720/11 which can be shortened to
                                                65.46 to save 1 byte.
                                      %60       mod 60
                                         |0     floor the result

Side note: I'm pretty sure this can be golf down by someone with more knowledge at math. I barely know how to sum and multiply
Try it online!

This doesn't look right if you take how a real clock works into action: http://datagenetics.com/blog/november12016/index.html

You have some rounding errors. 05:00 should output 05:27 but outputs 05:25 instead, and 06:45 should output 07:38 but outputs 07:35 instead. Here perhaps a useful oeis sequence: A178181

@LuisfelipeDejesusMunoz The two test cases I gave are indeed correct now, but your 11:56 seems to output 00:05 instead of 00:00 (or 12:00).

@KevinCruijssen Done. I think a=(a+=b>=a*5)%12 can be shorten a little bit but i'm not too good at this

@LuisfelipeDejesusMunoz Looks good! You can golf 4 bytes by changing the position of the %12: a=>b=>[a+=b>=a*5,a%12*65.45%60|0]

f(10)(56) is [11, 59]

Something else is also wrong since 10:50 also jumps 10:54 and gives the 11:59 output

Seems good (not sure if we are meant to "round half up" or whether we can round any way we want including a floor - see  my comments under the OP)

@LuisfelipeDejesusMunoz This gives the wrong answer for 6:30 > 6:33.

@mbomb007 yup, I was rounding towards 0 until OP clarified that part

Isn't Math.round(x) just 0|x+.5?

R, 68 bytes
a=round(1:30*720/11);a[a>sum(scan()*c(60,1))][1]%/%c(60,1)%%c(12,60)

Try it online!

-2 bytes thanks to Giuseppe
+7 bytes due to missing rounding :(

Exploiting the equation :
same_position_minutes = 720/11 * index

where index is 0 for the first overlapping position (00:00), 1 for the 2nd and so on...

I think you have an extraneous set of parentheses around (a[...]...c(60,1))

@Giuseppe: yep, you're right... thanks !

@digEmAll This gives the wrong answer for 6:30 > 6:33.

@mbomb007 : you're right, fixed ;)

J, 31 bytes
0.5<.@+>:@<.&.(11r720*12 60&#.)

Try it online!
The way to round a number in J is to add 0.5 and take the floor (<.). Takes too many bytes...

Explanation
12 60&#. (mixed base conversion) converts from an array of [hour, minute] to the minute passed since 0:00.
Note that starting from 0:00, every 12/11 hours (that is, 720/11 minutes), the two hands overlap once.
Therefore, given the minute value, just round it up to the nearest multiple of 720/11 (different from itself). This can be achieved by * it by 11/720 (J has rational number literal 11r720), take the floor <., increment >:, then multiply it by 720/11.
Note that "multiply by 11/720" and "multiply by 720/11" are 2 reverse action, as well as "convert from [hour, minute] to number of minute passed" and vice versa. Fortunately J has built-in &. (under), which reverses some action after applying a transformation.
After that just do the rounding: 0.5 + then <..

R, 88 bytes
i=scan();d=1+60*i[1]+i[2];while(abs(60*(h=d%/%60%%12)-11*(m=d%%60))>5){d=d+1};paste(h,m)

Try it online!
Increase time by one minute. Checks the angle. If not close enough, loops until a solution is found.

Huh, that's a cool way of doing it. I never thought of simulating an actual clock!

Python 3, 80 78 bytes
This is my first submission, so constructive criticism is welcome :)
-2 bytes thanks to @Jo King
def f(h,m):n=65.45;r=round(((60*h+m)//n%11+1)*n);print('%i:%02i'%(r//60,r%60))

Try it online! (78)
Try it online! (80)

Welcome to PPCG! Good first answer!

Java 8, 89 82 bytes
(h,m)->(m=m<(m=(int)(h%12*720d/11%60))?m:(int)(++h%12*720d/11%60))*0+h%12%11+" "+m

Fixed. Will see if I can golf it later (probably by porting another answer)..
Try it online.
Explanation:
TODO

Same issue (obviously) as the answer you ported - e.g.: f.apply(56).apply(10) yields 11 59

@JonathanAllan Fixed. Will see if I can remove some bytes later..

@KevinCruijssen This gives the wrong answer for 6:30 > 6:33.

@mbomb007 I know. I'm waiting for OP's response before fixing that. Whether we should floor, round, ceil, or both are allowed (if I would have posted the challenge I would use the fourth option, but let's wait for OP first).

@KevinCruijssen The test case was edited into the question because of a comment by the OP. Using the most common definition of round, the OP's intent is clear.

C# (.NET Core), 70 bytes
(h,m)=>{h%=12;int n=(5*h+h/2)%60;return (m>n||h>10)?f(h+1,0):h+":"+n;}

Try it online!
I think it passes all test cases. Although the h=11 case is kind of ugly
Explanation:
(h,m)=>{ // Lambda receiving 2 integers
    h%=12; // Just to get rid of the 0/12 case
    int n=(5*h+h/2)%60; // get the minute at which the hands overlap
                        //for current hour.
    return
    (m>n||h>10)? // if current minute > n or h=11
        f(h+1,0) // it will happen next hour
    :
        h+":"+n; // return result
}

This gives the wrong answer for 6:30 > 6:33.

@mbomb007 Thanks, I'm going to have a look on this. I did the first try before the complete list of overlap times was added.

It should be ok now. Since we don't have a clear instruction about what to do in cases where currentTime == overlapTime, I return the current time in these cases (given (1,5) return "1:5" and not "2:11").

Apl (Dyalog Unicode), 28 bytes
((⍳11),⍪0,+\∊5/⊂5 6)(⍸⌷1⊖⊣)⎕

Try it online!

Explanation
((⍳11),⍪0,+\∊5/⊂5 6) is a matrix of times where the hands overlap (printed at the end of the tio link)
(⍸⌷1⊖⊣)⎕ finds the interval in which the input is in the matrix and indexes below it wrapping around.

JavaScript, 41 bytes
p=>q=>(p+=q>=(5.5*p|0),p%=11,[p,5.5*p|0])

f =
p=>q=>(p+=q>=(5.5*p|0),p%=11,[p,5.5*p|0])

Input: <input type=number min=0 max=11 id=h style=width:40px value=0 autofocus>:<input type=number min=0 max=59 id=m style=width:40px value=0>

Output: <output id=o></output>

Jelly, 25 bytes
‘2¦ɓ;W}Ṣi¹ịḷø5,6ẋ5ÄĖØ0W¤;

Try it online!
A monadic link that takes the time as a two-integer list and returns a two-integer list corresponding to the next time the hands are due to touch.

Perl 6, 43 bytes
(* *60+*+33).round(65.45).round.polymod(60)

Try it online!
An anonymous Whatever lambda that takes two integers representing hours and minutes and returns the hours and minutes in reverse order. Right now it isn't consistent when you input an aligned time, whether it outputs the next aligned time or stays on the same one. I'm waiting on OP to respond on that matter, but right now I'm treating it as undefined.
Explanation
(* *60+*+33)   # Converts the two inputs to number of minutes
            .round(65.45)   # Round to the nearest multiple of 65.45
                         .round  # Round to the nearest integer
                               .polymod(60) # Repeatedly modulo by 60 and return the list of results

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Stack Exchange Stock Exchange - V3

NOTICE: This challenge is now closed: I will no longer be updating the leaderboard and will not change the accepted answer. However, you are free to run the controller and update the leaderboard yourself, if you wish.

Join the chat!
Introduction
Good evening, traders! You are all traders for the golfing company PPCG. Your task is to make as much money as possible.
Challenge
Write a program that buys and sells shares on the Stack Exchange Stock Exchange with the aim of making as much money as possible.
Gameplay
All players will start with 5 shares and $100 in their bank. The game always starts with a share price of $10.
Each game will have 1000 rounds where the first round is round 1. In each round, your program will be supplied four arguments as input: the current share price, the number of shares you hold, the amount of money you own and the round number (1-indexed).
For example, if my program is test1.py, the share price is 100, the number of shares I hold is 3, the amount of money I have is 1200, and the round number is 576, my program will be run like so:
python test1.py 100 3 1200 576

In a round, the share price given to each player will be the same. This doesn't change until the end of the round.
In response, the player must print their command. There are two options:

Buy shares: This command is given as bn where n is the number of shares you wish to buy. For example, if you want to buy 100 shares, you would output:

b100

When buying shares, you are allowed an overdraft of up to $1000. If you try to buy enough shares that exceed this overdraft (your bank balance goes below $-1000), you will be declared bankrupt. This means that you will lose all of your shares and your balance will be set to $50.
The share price will be unaffected by your command if you go bankrupt.
(If your balance is $-1000, you are not bankrupt. However if your balance is $-1001, you are bankrupt)

Sell shares: This command is given as sn where n is the number of shares you wish to sell. For example, if you want to sell 100 shares, you would output:

s100

You may not sell more shares than you own. If you try to do this, your request will be denied, and you will skip the round.
If you want to skip the round and do nothing, output either b0 or s0.
Your request will be denied if you try to buy or sell a negative number of shares and/or a non-integer number of shares.
After 5 rounds, at the end of each round, all players will be payed a dividend, the value of which is 5% of the mean average share price of the last 5 rounds.
How does it work?
Initially the share price will be $10. At the end of each round, it will be recalculated using the formula:
$$\text{New Share Price} = \text{Old Share Price} + (\text{Number of shares bought}-\text{Number of shares sold})$$
The share price will be limited so that it never falls below $1.
To prevent overly rapid change, the change in share price is limited to a maximum of \$\pm$200\$.
Rules

Your program must have a name

Your program is allowed a single text file for data storage. It must be stored in the same folder as your program

Include in your answer details of how to run your program

This KotH is open to all programming languages that are free-to-use and can be run on Windows 10

Your score is based solely on the contents of your balance. Any money locked up in shares will not be counted

You may edit your program at any time. Before each game, the latest code will be saved and compiled

You should not write code which specifically targets another bot.

Controller
The controller is written in Python and can be found here: https://gist.github.com/beta-decay/a6abe40fc9f4ff6cac443395377ec31f
At the end it will print a leaderboard and display a graph of how the share price changed throughout the game.
For example, when two random bots were playing

Winning
The player with the highest amount of money in their balance at the end of the last game wins.
Leaderboard
Game 4: 16:14 10/08/2018
Name                                Balance

Experienced Greedy Idiot            $14802860126910608746226775271608441476740220190868405578697473058787503167301288688412912141064764060957801420415934984247914753474481204843420999117641289792179203440895025689047561483400211597324662824868794009792985857917296068788434607950379253177065699908166901854516163240207641611196996217004494096517064741782361827125867827455285639964058498121173062045074772914323311612234964464095317202678432969866099864014974786854889944224928268964434751475446606732939913688961295787813863551384458839364617299883106342420461998689419913505735314365685264187374513996061826694192786379011458348988554845036604940421113739997490412464158065355335378462589602228039730
Equalizer                           $763185511031294813246284506179317396432985772155750823910419030867990447973211564091988995290789610193513321528772412563772470011147066425321453744308521967943712734185479563642323459564466177543928912648398244481744861744565800383179966018254551412512770699653538211331184147038781605464336206279313836606330
Percentage Trader                   $448397954167281544772103458977846133762031629256561243713673243996259286459758487106045850187688160858986472490834559645508673466589151486119551222357206708156491069820990603783876340193236064700332082781080188011584263709364962735827741094223755467455209136453381715027369221484319039100339776026752813930
OYAIB                               $8935960891618546760585096898089377896156886097652629690033599419878768424984255852521421137695754769495085398921618469764914237729576710889307470954692315601571866328742408488796145771039574397444873926883379666840494456194839899502761180282430561362538663182006432392949099112239702124912922930
Chimps on a Typewriter              $176504338999287847159247017725770908273849738720252130115528568718490320252556133502528055177870
Greedy B*****d                      $17689013777381240
Illiterate Dividend Investor        $2367418699671980
Lucky Number 6                      $4382725536910
Lone Accountant                     $90954970320
Buy/Reinvest                        $127330
Technical Analysis Robot            $126930
Dollar Cost Averager                $106130
Fibonacci                           $69930
Novice Broker                       $28130
Buy Low                             $6130
Naive Statistician                  $6130
Fallacious Gambler                  $6130
Passive Trader                      $4980
Half More or Nothing                $4920
Monkeys on a Typewriter             $66

View graphs of each contestant

Related but the gameplay and winning criterion are very different to this challenge.

Comments are not for extended discussion; this conversation has been moved to chat.

For me the formula shows as [Math Processing Error] in red. Is it the same for others as well? If so maybe it's an issue with the question.

@CaptainMan I see it fine

It might be worth averaging results over say, 10-100 games to reduce the influence of luck. Or maybe that would be changing the challenge too much.

Would it be possible to have the scores be log2/log10? It would make it much easier to compare the scores. (I browse with my phone, and the exponents disappeared off screen)

I think that even 10-100 is too few, but I like to run a lot of games.  To make that possible, you'd need to change the format of the challenge, which is out of scope now.

You should modify the controller so it forces values to be integers. Right now, if it gets a value with an exponent ie: 1e100 it will use that as a float and start using floats for everything. This will break just about all of the programs.

this game is... not how stocks work at all :P

@BenMillwood if you want a real stock market go look at the other stock exchange koth

The Experienced Greedy Idiot
PHP, tested on PHP >= 7, should work on previous ones as well.
<?php

class StickExchange
{
    private $dbFile;
    private $sharePrice;
    private $shares;
    private $balance;
    private $overdraft;

    public function __construct($sharePrice, $shares, $balance, $round)
    {
        $this->dbFile = __FILE__ . '.txt';
        $this->sharePrice = gmp_init($sharePrice);
        $this->shares = gmp_init($shares);
        $this->balance = gmp_init($this->parseScientificNotationToInt($balance));
        $this->overdraft = gmp_init(1000);

        $action = 'b';

        if ($round == 1) {
            $this->buy();
        } elseif ($round == 1000) {
            $this->sell();
        } else {
            $content = $this->getDbContent();
            $lastPrice = gmp_init($content['price']);
            $secondLastPrice = gmp_init($content['last_price']);
            $lastAction = $content['action'];

            $shareAndLastCmp = gmp_cmp($this->sharePrice, $lastPrice);
            $lastAndSecondLastCmp = gmp_cmp($lastPrice, $secondLastPrice);

            if ($shareAndLastCmp > 0 && $lastAndSecondLastCmp > 0) {
                if ($lastAction == 'b') {
                    $this->sell();
                    $action = 's';
                } else {
                    $this->buy();
                }
            } elseif ($shareAndLastCmp < 0 && $lastAndSecondLastCmp < 0) {
                if ($lastAction == 'b') {
                    $this->sell();
                    $action = 's';
                } else {
                    $this->skip();
                }
            } elseif ($shareAndLastCmp > 0) {
                $this->sell();
                $action = 's';
            } elseif ($shareAndLastCmp < 0) {
                $this->buy();
            } else {
                $this->skip();
            }
        }

        $this->setDbContent([
            'action' => $action,
            'price' => gmp_strval($this->sharePrice),
            'last_price' => isset($lastPrice) ? gmp_strval($lastPrice) : '0',
        ]);
    }

    private function parseScientificNotationToInt($number)
    {
        if (strpos($number, 'e+') !== false) {
            $sParts = explode('e', $number);
            $parts = explode('.', $sParts[0]);
            $exp = (int)$sParts[1];

            if (count($parts) > 1) {
                $number = $parts[0] . $parts[1];
                $exp -= strlen($parts[1]);
            } else {
                $number = $parts[0];
            }

            $number = gmp_init($number);
            $pow = gmp_pow(gmp_init(10), $exp);
            return gmp_strval(gmp_mul($number, $pow));
        } elseif (strpos($number, 'e-') !== false) {
            return sprintf('%d', $number);
        } else {
            $parts = explode('.', $number);
            return $parts[0];
        }
    }

    private function getDbContent()
    {
        return unserialize(file_get_contents($this->dbFile));
    }

    private function setDbContent($content)
    {
        file_put_contents($this->dbFile, serialize($content));
    }

    private function buy()
    {
        $realBalance = gmp_add($this->balance, $this->overdraft);
        $sharesToBuy = gmp_div($realBalance, $this->sharePrice);
        $this->stdout('b' . gmp_strval($sharesToBuy));
    }

    private function sell()
    {
        $this->stdout('s' . gmp_strval($this->shares));
    }

    private function skip()
    {
        $this->stdout('b0');
    }

    private function stdout($string)
    {
        $stdout = fopen('php://stdout', 'w');
        fputs($stdout, $string);
        fclose($stdout);
    }
}

new StickExchange($argv[1], $argv[2], $argv[3], $argv[4]);

An updated version of "The Greedy Idiot" with re-structured behavior and bug fixes related to working with huge numbers.
Notes:

Save in a file and run it like this: php C:\path\path\stack_exchange.php 10 5 100 1
This script creates a text file with same name as the script file and a .txt appended to the end. So please run with an user with appropriate write permission on the script path.
A simple how to install PHP 7.2 on windows: http://www.dorusomcutean.com/how-to-install-php-7-2-on-windows/
To work with super huge numbers, I had to use GMP, so these two lines on php.ini should be un-commented (the semi-colon at start of line should be removed, if it isn't already):

; extension_dir = "ext"
;extension=gmp

Wow, thanks for that link! I was wondering :D

@BetaDecay: No problem, btw you only need to go until the step 2 (Test PHP is installed) where you check your installation with php -v. The rest aren't needed for this. I believe you are going to have lots of trouble with setting up so many different languages for this challenge! I would never dare to do something like this :D

@BetaDecay wouldn't it be easier to just install TryItOnline as a Docker container?

@NieDzejkob Possibly but it'll probably come in handy having these languages installed

Congrats, you consistently beat every other contestant!

Thank you! Wish I could use some of those dollars in real world :P

Chimps On A Typewriter
import random
from sys import argv

share_price = int(argv[1])
share_count = int(argv[2])
balance = float(argv[3])

x = random.random()
if x < 0.5:
    max_buy = balance / share_price
    buy_count = int(max_buy * random.random())
    print('b' + str(buy_count))
else:
    sell_count = int(share_count * random.random())
    print('s' + str(sell_count))

Chimps are smarter than monkeys, they won't buy stocks they can't afford, or sell stocks they don't have.
Still pretty random otherwise though.
Run with python3, but should(?) work with python2 as well

They may be smarter, but are they luckier?

In all of my tests this one has come out on top, so yes

I'm extremely curious how this won the first round by more than 20 orders of magnitude

I like to put it down to the art of simplicity. Everyone else is over-engineering their bots.

This got so much love, by mistake :P

OYAIB
from sys import argv

share_price = float(argv[1])
shares      = int(argv[2])
cash        = float(argv[3])
cur_round   = int(argv[4])
tot_rounds  = 1000.0

investments = shares * share_price
total_assets = investments + cash

target_cash = round(cur_round / tot_rounds * total_assets)

if target_cash > cash:
  shares_to_sell = min(shares, round((target_cash - cash) / share_price))
  print('s%d' % shares_to_sell)
else:
  shares_to_buy = round((cash - target_cash) / share_price)
  print('b%d' % shares_to_buy)

Following the old saying of "own your age in bonds," this program tries to do the same. This way we aren't subject to market volatility at the end-game.
Edit: Looking at the controller it shows that we can only buy/sell full shares, but can have a fractional account balance.

Welcome to PPCG!

Thank you! First time posting so let me know if anything is out of place.

You might want to add an extra condition that on the last round, you sell all of your shares (as investments aren't counted in your score).

That's the beauty of OYAIB, it does that automatically. The target_cash is a percentage of the total_assets depending on what point in "life" it's at. At the end of life, target_cash is 100% of total_assets, so it will sell any shares it's holding.

Lone Accountant
buy-sell.py:
from sys import argv

Price = int(argv[1])
Shares = int(argv[2])
Balance = float(argv[3])
Round = int(argv[4])

if Round % 2 == 0: print('s' + str(Shares))
if Round % 2 == 1: print('b' + str(int((Balance + 1000) / Price)))

Doesn't store anything in buy-sell.txt.
In odd rounds, it buys as many shares as it can. In even rounds, it sells all of its shares.
The intent is to first raise the share price by buying as many shares as possible, and then sell those shares to get more money. It works because the final round is even (round 1000).
Even though the share price will remain the same (5) after each pair of rounds (assuming the bot is alone, therefore Lone Accountant), the bot's balance increases, since the selling price is higher than the buying price, and more balance leads to the ability of buying more shares. It's a vicious cycle, but in a good way (for me).
The major vulnerability comes with evil bots playing alongside, selling in order to lower the share price (not sure if it's good for them either). In this case, the bot may remain with a balance of $-890, provided there are enough evil bots. This accountant really wants their peace of mind. ;-)

1 on 1 I'm not sure if beating this is possible; it isn't easy even if you fully understand the accountant LA and try to counter it.  In a mass game where you are outnumbered you could be outmaneuvered.

@Yakk Others have already beaten this in my test runs.

1 on 1?  I am puzzled; I am unable to work out how an opponent you can get rich enough to invert the price swings, or even prevent them from growing in magnitude over time without burning a pile of resources (meanwhile LA doesn't make the sacrifice, so becomes harder to stop).  Can you link to the gameplay that LA lost one-on-one?

@Yakk I haven't tested it one-on-one yet. Also, there's a chat room for us to discuss it if you want.

Would it be more robust to do nothing if you have shares and the price is lower than the previous round or you have money and the price is higher? It would guard against being out of sync with other, similar bots. Also, I don't see how this could be beaten one-on-one.

@JollyJoker I might make a separate answer. Already planned. Yeah, automatic protection may or may not be a good idea.

The Passive Trader
from sys import argv

share_price = int(argv[1])
balance = float(argv[3])
round_num = int(argv[4])

if round_num == 1:
    print('b%s' % str(int(balance / share_price)))
else:
    print('b0')

This guy isn't big on this whole "Stocks" thing, but he heard that if he just spends a little money now, he'll get little bits of money over time that'll add up to more than he spent.
He'll buy enough stocks to go to $0 (no overdraft for this fella, he's not gunna put himself in debt for a little profit), then sit around letting the dividends build
Run with python3, but should(?) work with python2 as well.

I think you should sell your 15 stocks in the last round at least.

@Kaldo nah, he's long forgotten about that one time he bought stocks by that point

Monkeys On A Typewriter
import random

cmd = ['b', 's'][int(random.random() * 2)]
num = str(int(random.random() * 1000000))
print("%s%s" % (cmd, num))

It's a bunch of monkeys on typewriters.
Randomly sells or buys X stocks, where:
0 <= X <= 1,000,000
Run with python3, but should(?) work with python2 as well

Why not use cmd=random.choose(['b','s']) and num = str(random.randint(0, 1000000))?

Because I'm lazy

why not just import lazy

the whole thing could be reduced to from random import randint, choice;print("{}{}".format(choice(["b", "s"]), randint(0, 1e6))) ;-P

yes, but this isn't a golf challenge

indeed not, which is why i left spaces in ;-) but not being a golf challenge is no excuse for the unused import :-D (smiley overload to demonstrate complete lack of seriousness)

Buy Low
(Python 2 or 3)
import random

def run(price, shares, balance, round_):
    # We get no value from our leftover shares at the end, so sell them all.
    if round_ == 1000:
        print('s' + str(int(shares)))
        return

    # If the price is low enough, buy everything we can.
    if price <= 20 + round_ * 60:
        print('b' + str((balance + 1000) // price))
        return

    # If we have no shares, wait for the price to drop.
    if shares == 0:
        print('b0')
        return

    # Sometimes sell shares so we can buy if the price gets low again.
    if random.random() < 0.4:
        print('s1')
        return

    # Otherwise, just wait for a better price.
    print('b0')

if __name__ == '__main__':
    import sys
    run(*[float(x) for x in sys.argv[1:]])

The Naïve Statistician
Made for Python 3, might work in Python 2
from sys import argv
from math import floor

# Save an entry to the stock history
def save_history(price):
    with open('stockhistory.txt', 'a') as f:
        f.write(str(price) + '\n')

# Load the stock history
def load_history():
    with open('stockhistory.txt', 'r') as f:
        return [float(line.strip()) for line in f]

# Calculate average price rise/fall streak length
def average_streak(history, condition):
    streaks = []
    current_streak = 0
    last_price = history[0]
    for price in history[1:]:
        if condition(last_price, price):
            current_streak += 1
        elif current_streak:
            streaks += [current_streak]
            current_streak = 0
        last_price = price
    if current_streak:
        streaks += [current_streak]
    return sum(streaks) / len(streaks) if streaks else None

# Calculate the current streak length
def current_streak(history, condition):
    streak = 0
    while streak < len(history) - 1 and condition(history[-streak - 2], history[-streak - 1]):
        streak += 1
    return streak

def run(share_price, share_count, balance, round_number):
    save_history(share_price)

    # Sell all shares if it is the last round
    if round_number == 1000:
        print('s' + str(int(share_count)))
        return

    # Buy as many shares as possible if the price is down to one, as there's
    # nothing to lose
    if share_price == 1:
        buy_count = int(balance + 1000)
        print('b' + str(buy_count))
        return

    history = load_history()

    # Calculate the average and current rise/fall streaks
    average_rise = average_streak(history, lambda a, b: a <= b)
    current_rise = current_streak(history, lambda a, b: a <= b)
    average_fall = average_streak(history, lambda a, b: a >= b)
    current_fall = current_streak(history, lambda a, b: a >= b)

    # Do nothing if there's no analyzed data
    if not average_fall or not average_rise:
        print('b0')
        return

    # Buy shares if the current rise streak is as long as or longer than average
    if current_rise > current_fall and current_rise >= average_rise:
        buy_count = (balance + 1000) / share_price
        print('b' + str(int(buy_count)))
        return

    # Sell shares if the current fall streak is as long as or longer than average
    if current_fall > current_rise and current_fall >= average_fall:
        print('s' + str(int(share_count)))
        return

    # Otherwise, do nothing
    print('b0')

run(*map(float, argv[1:]))

This is a naïve statistician that tries to predict stock prices by only buying/selling if the price has risen/fallen for longer than usual, while also buying stocks if the price is down to one and selling all stocks on the last round.

Percentage Trader Python3
(maybe works in python2)
import sys
args=sys.argv

price=int(args[1])
held=int(args[2])
money=int(args[3])
roundNum=int(args[4])
prevPrice=0

if roundNum==1:
    print("b"+str((money+1000)//price))
else:
    if roundNum==1000:
        print("s"+str(held))
    else:
        with open("percentageTrader.dat","r") as f:
            prevPrice=int(f.read())
        if(price>prevPrice):
            toSell=int(held*int(1000000*(price-prevPrice))/(price))//1000000
            print("s"+str(toSell))
        if(price<prevPrice):
            toBuy=int(((money+1000)//price)*int(1000000*(prevPrice-price))//(prevPrice))//1000000
            print("b"+str(toBuy))
        if(price==prevPrice):
            print("b0")

with open("percentageTrader.dat","w") as f:
    f.write(str(price))

Instructions on running

Save as filename.py
Run with python filename.py price #shares balance round#

How it works

First round the bot purchases as many shares as it can afford.
If the price increases, the bot sells a percentage of shares equal to the percentage increase in price(calculated from new value)
If the price decreases, the bot buys a percentage of the maximum shares it could buy equal to the percentage decrease in price(calculated from previous value)
Sells off everything at round 1000

Changes should hopefully remove the problems caused by floating point division

Equalizer
from sys import argv
p, n, b, r = map(int, argv[1:])
c = p*n
print "bs"[(c+b)/2>b] + str(int(abs(((c-b)/2)/p))) if r < 999.5 else "s" + str(int(n))

Partitions its financial resources equally between cash and stocks on every round except the last. I believe this strategy to be a mathematically sound way of making at least some money, but I may be proven wrong.
There may or not be bugs that I haven't caught. Also golfed somewhat.

Your program is having difficulties with the large numbers involved here, so I'd suggest changing the line p, n, b, r = map(float, argv[1:]) into p, n, b, r = map(int, argv[1:])

@BetaDecay done

Fallacious Gambler
(Python 2 or 3)
import random

def run(price, shares, balance, round_):
    # We get no value from our leftover shares at the end, so sell them all.
    if round_ == 1000:
        print('s' + str(int(shares)))
        return

    # For the first round, just watch.
    if round_ == 1:
        with open('fg.txt', 'w') as f:
            f.write('1 0 10')
        print('b0')
        return

    # Get the state.
    with open('fg.txt') as f:
        direction, streak, previous = map(int, f.read().strip().split())
    change = price - previous

    # If the market isn't moving, wait for it to get hot again.
    if change == 0:
        print('b0')
        return

    # Keep track of the market direction.
    if (change > 0) == (direction > 0):
        streak += 1
    else:
        streak = 0
        direction *= -1

    # If the market's been going one way for too long, it has to switch, right?
    if streak > 5:
        if direction > 0:
            print('s' + str(shares // 2))
        else:
            print('b' + str((balance + 1000) // price // 2))
    # Otherwise, the market's too volatile.
    else:
        print('b0')

    # Save the state.
    with open('fg.txt', 'w') as f:
        f.write('%d %d %d' % (direction, streak, price))

if __name__ == '__main__':
    import sys
    run(*[float(x) for x in sys.argv[1:]])

The Dollar Cost Averager
(tested with Python 3.7)
First post in codegolf so tell me if I did something wrong.
The basic idea is to buy one share each round if that's possible and sell all shares at the end.
from sys import argv
share_price = int(argv[1])
share_count = int(argv[2])
balance = float(argv[3])
round = int(argv[4])

if round < 1000:
    if balance > share_price-1000:
        print("b1")
    else:
        print("b0")
else:
    print("s" + str(share_count))

The (Dyalog) APL Farmer
r←apl_stock_farmer args
 round←¯1↑args
 :If 1=round
     (buyPrice sellPrice)←10 0
     bought←1
     (currPrice shares balance)←3↑args
     r←'b10'
 :ElseIf 1000=round
     r←'s',⍕shares
 :Else
     (currPrice shares balance)←3↑args
     :If (currPrice>buyPrice)∧bought
         bought←0
         sellPrice←currPrice
         r←'s',⍕shares
     :ElseIf (currPrice<sellPrice)∧~bought
         bought←1
         buyPrice←currPrice
         r←'b',⍕⌊(1000+balance)÷currPrice
     :Else
         r←'b0'
     :End
 :End

A TradFn which buys every possible share on the first round, and only sells when the current price of the shares is higher than the price they were bought for. After selling, the bot will only buy shares that are cheaper than the price it last sold shares for.
That's because the farmer's accountant told him that's how you do stock trading. "Buy low, sell high" and all that stuff.
Disclaimer
This is my first attempt at a KotH challenge, and since I basically only do APL here, I decided to go on with it.
That said, I'm not completely sure if this will be able to be run alongside the other bots, since it's a Tradfn and can't be fed directly into a CMD/Bash shell.
So, to run this in Bash, you need the following command:
$ echo apl_stock_farmer args | dyalog 'stock_exchange.dws' -script
Where:
apl_stock_farmer is the name of the function, which is in the first line of code.
args is a vector of space separated arguments (in the first round, it would be 10 5 100 1).
dyalog is the path to the Dyalog executable
'stock_exchange.dws' is the name (or path, if the file is not in the same directory the shell has open) of the workspace that contains the function. That workspace file can be obtained by opening a clear workspace, typing )ed apl_stock_farmer, pasting the code above and then doing a )save <path>. I can also provide this workspace file if that would be easier.
-script is just an argument that makes dyalog execute the given code and print to stdout without actually opening the REPL.
Unfortunately, I haven't found a way to make it work with the Windows CMD or Powershell, so I ran it using Git Bash.
I'm not sure how feasible it is to put this bot on the competition, but I like this code way too much not to post it.

Sorry, I only have the unregistered version of Dyalog APL, so I'm not sure that this will work as an entrant to the competition

@BetaDecay I understand, no problems there. I also found out you can use the Pynapl library to run this code. The details are under "Accessing APL from Python", specifically "Defining a tradfn using Python", and it looks pretty straightforward.

Illiterate Dividend Investor
import random
from sys import argv

price = float(argv[1])
shares = int(argv[2])
cash = float(argv[3])
round = int(argv[4])

# buy 1st round, sell last round
if round == 1:
    print('b' + str(int((cash + 1000) / price)))
elif round == 1000:
    print('s' + str(shares))

# round right before dividend: sell
elif round % 5 == 4:
    print('s' + str(shares))

# 1 round after dividend: buy
elif round % 5 == 0:
    print('b' + str(int((cash + 1000) / price)))

# 2 rounds after dividend: 50/50 sell/try to buy
elif round % 5 == 1:
    if random.random() < 0.5:
        print('s' + str(shares))
    else:
        print('b' + str(int((cash + 1000) / price)))

# 3 rounds after dividend: sell if own shares (didn't sell last round), else buy
elif round % 5 == 2:
    if shares > 0:
        print('s' + str(shares))
    else:
        print('b' + str(int((cash + 1000) / price)))

# otherwise, 4 rounds after dividend, buy
else:
    print('b' + str(int((cash + 1000) / price)))

Assumes after dividends, people have more cash, so they will be more likely to buy. Sells right before dividends, buys right after. Goes through one other sell/buy cycle in the other 3 rounds.

Looking at the controller, the dividends pay out every round after the 4th, not only every 5th round. Your cycle should still work but probably not as you intended.

If you buy after other people buy you end up buying when more expensive.

Thanks @Veskah. Had to add in some r1/r1000 logic as well.

@fəˈnɛtɪk - assuming people buy the round after dividends, you too would want to buy that round and then sell afterward, no?

There is also no round after dividends as you get dividends every round after the 4th.

Oh man. Reading is hard. Thanks @fəˈnɛtɪk. It's almost the weekend, I'm just going to leave it up and see what happens.

You have a minor typo on line 13, pring :)

Novice Broker (but gets the basic idea)
se_stock_exchange.rb:
DATA_FILE = $0.sub /\.rb$/, ".data"
NUM_ROUNDS = 1000

share_price, num_shares, money, round = ARGV.map &:to_i

order = "s0"

if round == NUM_ROUNDS
  puts "s#{num_shares}"
  exit
end

if File.exists? DATA_FILE
  last_price, trend, bought_price = File.read(DATA_FILE).lines.map &:to_i
else
  last_price = 0
  trend = -1
  bought_price = 0
end

if (new_trend = share_price <=> last_price) != trend
  case trend
  when -1
    order = "b#{(money + 1000) / share_price}"
    bought_price = [bought_price, share_price].max
  when 1
    if share_price > bought_price
      order = "s#{num_shares}"
      bought_price = 0
    end
  end
  trend = new_trend
end

File.open(DATA_FILE, "w") { |f| f.puts share_price, trend, bought_price }

puts order

Waits until the price turns around, then buys/sells everything. I mean, that's what it says to do in Day Trading for Dummies Note: this is probably a real book, and that's probably something someone might get from it.
Saves data in se_stock_exchange.data. Run with ruby se_stock_exchange.rb ${SHARE_PRICE} ${SHARES} ${MONEY} ${ROUND} (substituting the appropriate values).

This is my first stab at KotH, so let me know if I'm doing it all wrong.

Nice: https://www.amazon.co.uk/Day-Trading-Dummies-Ann-Logue/dp/047094272X

I get this error: se_stock_exchange.rb:24:in `<main>': undefined method `+' for nil:NilClass (NoMethodError)

Ah, I wasn't clear with the run instructions. Needs the arguments passed in.

@BetaDecay: Too bad the author's middle name doesn't start with an 'A'.

@NieDzejkob: If it were an 'A': "Ann A. Logue" is analogous to "Analog".

Buy/Reinvest as much as possible!
Similar to my Dollar-Cost Averager that did, surprisingly,  quite average, this buys each round as many shares as are affordable and only sells them in the last round.
from sys import argv

share_price = int(argv[1])
share_count = int(argv[2])
balance = float(argv[3])
round = int(argv[4])

if round < 1000:
    if balance > share_price-1000:
        buy_count = int((balance+1000)/share_price)
        print("b"+str(buy_count))
    else:
        print("b0")
else:
    print("s" + str(share_count))

Hey, you've got an error with your indentation here. Did you mean to indent the if balance > share_price-1000: block or not?

Yes. My minor edit seems to have disrupted my formatting. Will fix as soon as I'mback on a pc

Half More or Nothing
def run(price, shares, balance, cur_round):
    if cur_round==1000:
        print('s'+str(int(shares)))
        return

    if cur_round==1:
        with open('HalfMoreOrNothing.dat', 'w') as f:
            f.write(str(int(price)))
        print('b'+str(int((balance+1000)/price)))
        return

    if shares==0:
        with open('HalfMoreOrNothing.dat', 'w') as f:
            f.write(str(int(price)))
        print('b'+str(int((balance+1000)/price)))
        return

    with open('HalfMoreOrNothing.dat', 'r') as f:
        bought_price=int(f.read())
    if price>=bought_price*1.5:
        print('s'+str(int(shares)))
        return

    print('b0')

if __name__ == '__main__':
    import sys
    run(*[float(x) for x in sys.argv[1:]])

I rarely use Python, let me know if this generates an error somewhere.
The strategy is to wait until the share price is at least 50% bigger than the price at the moment of bying them, then sell them, then immediately buy new shares so it can wait for the new share price raise.
Hopefully, people chimps won't start to sell shares near the end... (it seems that most bots just wait for the right moment, whatever that is)

Fibonacci
I've rewritten this in Python 3 to make things easier. Hopefully!
import math
from sys import argv

price = float(argv[1])
shares = int(argv[2])
balance = float(argv[3])
roundNum = int(argv[4])

fibonacci = [2,3,5,8,13,21,34,55,89,144,233,377,610,987]
if (roundNum == 1):
    buy = int((balance+1000)/price)
    print('b' + str(buy))
elif (roundNum in fibonacci) and roundNum % 2 == 1 and balance > 0:
    buy = int((balance/price)/2)
    print('b' + str(buy))
elif ((roundNum in fibonacci) and roundNum % 2 == 0) or roundNum % 100 == 0:
    if (roundNum == 1000):
        sell = shares
        print('s' + str(sell))
    else:
        sell = math.ceil(shares/2)
        print('s' + str(sell))
else:
    print('b0')

It buys half the maximum amount of shares that is affordable when the round is equal to an odd Fibonacci number and sells half of the available shares when the round is equal to an even Fibonacci number and also every 100 rounds. Sells all shares on round 1000. Otherwise, it just waits. Only buys shares when balance is positive.

Hey, I get the error Error in roundNum%%2 : non-numeric argument to binary operator                                                                                Execution halted

@BetaDecay I updated the code which may fix the issue. Let me know.

Technical Analysis Robot
I study business economics so I tried to realize the simpliest method for analizing a stock market (the technical analysis). According to the theory you just have to analyze all the minimums of the graph to see if there is a trend (up ord down). During an up trend you have to buy and during a down trend you have to sell.
I don't think that this method will work too well but let's give it a try :)
import sys
from sys import argv

share_price = int(argv[1])
share_number = int(argv[2])
bank_account = float(argv[3])
round_number = int(argv[4])

max_buy_greedily = (1000 + bank_account) / share_price
minima = []

def log():
    f = open("log_technical_analysis.txt","a+")
    f.write("%d;" % share_price)

def analyze():
    f = open("log_technical_analysis.txt","r+")
    line = f.readline()
    values = line.split(";")
    values.pop()
    for i in range(len(values) - 1):
        if i > 0 and int(values[i-1]) > int(values[i]) and int(values[i+1]) > int(values[i]):
            minima.append(int(values[i]))
    if len(minima) >= 3 and minima[len(minima) - 1] > minima[len(minima) - 2] and minima[len(minima) - 2] > minima[len(minima) - 3]:
        print('b' + str(int(max_buy_greedily)))
    elif len(minima) >= 3 and minima[len(minima) - 1] < minima[len(minima) - 2] and minima[len(minima) - 2] < minima[len(minima) - 3]:
        print('s' + str(share_number))
    else:
        print('b0')

if round_number >= 994:
    print('s' + str(share_number))
    sys.exit(0)

if share_price <= 15:
    print('b' + str(int(max_buy_greedily)))
    log()
    sys.exit(0)

log()
analyze()
sys.exit(0)

Tested with python3

Good luck! This is far from a normal market :D

@BetaDecay haha yeah :] but you would be wondering how random most of the people spend their money in the stock market (or bitcoin) :D

Lucky Number 6
EDIT: Oh ffs, I think me not converting the selling count to int was one of my problems, well here we go again.
Probably my last contribution, unless I'm bored at work and make something a bit more sophisticated, but I fell like the sophisticated bots already fill the niches.
This guy basically sells some of his shares every 6 rounds, because hey 6 is his lucky number.
from sys import argv
import random

share_price = int(argv[1])
share_count = int(argv[2])
balance = float(argv[3])
round = int(argv[4])
x = random.uniform(1,2)

if round == 1 or round == 1000:
    print("s"+str(share_count))
elif round % 6 == 0 and share_price >= 10:
    sell = int(share_count/x)
    print("s"+str(sell))
elif balance > share_price-1000:
    buy_count = int((balance+1000)/share_price)
    print("b"+str(buy_count))
else:
    print("b0")

Greedy B*****d
# Gready one...
from sys import argv

SMA_PERIOD = 5
LAST_BUY_DAY = 985
LAST_SELL_DAY = 993

# Save an entry to the stock history
def save_history(price):
    with open('db.txt', 'a') as f:
        f.write(str(price) + '\n')

# Load the stock history
def load_history():
    with open('db.txt', 'r') as f:
        return [float(line.strip()) for line in f]

def get_sma(d, n):
    l = d[-n:]
    return int(sum(l) / len(l))

def buy(price, account):
    if account + 1000 > 0:
        print 'b' + str(int((account + 1000) / price))
        return
    print 'b0'

def sell(holdings):
    print 's'+ str(int(holdings))

def run(price, holdings, account, day):

    save_history(price)
    d = load_history()

    if price <= get_sma(d, SMA_PERIOD) and day < LAST_BUY_DAY:
        return buy(price, account)

    if price > get_sma(d, SMA_PERIOD):
        return sell(holdings)

    if day >= LAST_SELL_DAY:
        return sell(holdings)

    # Otherwise, do nothing
    print 'b0'

run(*map(float, argv[1:]))

He will go all in when its cheap and sell it all once the price goes up...

Your code is all over the place. Firstly, you return print statements but also you pass three arguments to sell() which only takes one

Typo with three args to sell()... now whats your concern with returning print statements?

Just that they’re unnecessary

some argue they help with readability

you didnt include it in results because of prints? afaik typo in sale() definition wont stop it working... I fix that by the way

I didn’t include it because of the typo in sale() - it kept throwing an error

aah right then, sorry for that. I'll check it again and edit answer if needed

I've just fixed it... code was all over the place. apologies


text:
Roman Army Shields
Sandbox post (deleted)
The old roman army formations are very famous around the world. In these formations roman legionaries grouped in a geometric shape (usually a rectangle) protecting the flanks and the superior part of it using their shields. The legionaries at interior positions covered the superior part placing their shield above their heads, the legionaries at the flanks carried 2 or more shields: one for protecting the superior part, and one or more shields for protecting the flanks (if someone was in the corner he had 3 shields, if someone was alone in a formation he had 5 shields Yes, I know it is impossible for a human to carry 5 shields, but somehow they did it). Using this formation all roman legionaries protected themselves and were the hardest opponent at the time.
The history tells there was a roman general who stated that the best formation shape was the square (same number of legionaries in rows and columns). The problem was figuring out how many formations (and the size) he should split his army in order to:

Do not left any legionary out of a formation (although he admitted single legionary formation)
Reduce the amount of required shields

The general, after doing some math and calculations, he figured out that the best way to accomplish this 2 conditions is to start with the biggest square possible, and then repeat until no legionaries left.

Example:
If 35 legionaries in his army, the formation consisted in

A 5x5 legionaries square (This is the biggest square possible).

With the remaining legionaries (10)

A 3x3 square

With the remaining legionaries (1)

A 1x1 square.

At the end it will look something like this:
   5x5
* * * * *        3x3
* * * * *       * * *      1x1
* * * * *       * * *       *
* * * * *       * * *
* * * * *

The legionaries at interior positions covered the superior part placing their shield above their heads. They only needed 1 shield.
* * * * *
* 1 1 1 *       * * *
* 1 1 1 *       * 1 *       *
* 1 1 1 *       * * *
* * * * *

The legionaries at the flanks carried 2
* 2 2 2 *
2 1 1 1 2       * 2 *
2 1 1 1 2       2 1 2       *
2 1 1 1 2       * 2 *
* 2 2 2 *

If someone was in the corner he had 3 shields
3 2 2 2 3
2 1 1 1 2       3 2 3
2 1 1 1 2       2 1 2       *
2 1 1 1 2       3 2 3
3 2 2 2 3

If someone was alone in a formation he had 5 shields
3 2 2 2 3
2 1 1 1 2       3 2 3
2 1 1 1 2       2 1 2       5
2 1 1 1 2       3 2 3
3 2 2 2 3

This formation required a total of 71 shields.

Challenge

Calculate the amount of shields that are needed for a X amount of legionaries

Input

Amount of legionaries in the army

Output

Amount of shields needed.

Test Cases
35 => 71
20 => 44
10 => 26
32 => 72

Standard code-golf rules apply

How... How does one carry 5 shields? 2 in each hand, 2 in each foot and one in his mouth?

@MagicOctopusUrn I can not sleep at nights only thinking about that xD

Well the google result for "carrying 5 shields" is Amazon.com : Best-selling Nipple Shield Carrying Case, Perfect... so I guess I'll never truly know. Did they actually carry 5 shields-- or was this to make the question work :P?

@MagicOctopusUrn They would likely never be on their own.

@Okx I assumed-- but my only knowledge about shield walls begins and ends with the movie 300 hah!

@MagicOctopusUrn Im pretty sure you know the answer xD I don't think someone has the guts to go out in a fight with 5 shields

History has taught me not to underestimate the Romans hehe :).

Not that it's really helpful, but A028347 gives the number of shields for a given square.

Not that historicity matters here, but your description of what is called a testudo formation is not quite right. The flanks and back of the formation were typically left unshielded, with only the front and top of the formation remaining shielded. Each soldier would have only carried one shield.

I don't the general's math and calculations are right to conclude that repeatedly taking the largest square possible necessary minimizes shields. For example, 32 legionaries can split into two 44 squares for 64 total shields, rather than squares of 55 + 22 +11 + 11 + 11 for 72 total shields.

@xnor you are right, it is not the best way to minimize the amount of shields (it was discussed in the sandbox) but the general is the general.

@xnor Maybe in general case the general was't right, but the general is the general (although we shouldn't generalize).

But... what about attacks from below?

@AJFaraday Asterix and the mercenary badgers?

Python 2, 60 50 48  bytes
def f(s):n=s**.5//1;return s and(n+4)*n+f(s-n*n)

Try it online!
New to code golf, but giving it my best swing!
Method:
Sum n^2 + 4n where n is each of the largest square numbers that sum to the input.
Edit 1
Reduced to 50 bytes thanks to @Jonathan Frech!
Edit 2
Switched int(s**.5) to s**.5//1 to save 2 bytes thanks to @ovs

Welcome to PPCG!

You can use Try it online!, set up by one of our mods, Dennis, to give a testing environment for your solution; additionally if you click the "share" button, it will auto-format answers for you! I second @Luis's welcome, and I hope you enjoy participating on PPCG! :-)

I think n*n is shorter than n**2 to save you two bytes; more than that I can't say since I don't write python...

50 bytes.

Great first effort and welcome on board.

int(s**.5) can be shortened to s**.5//1.

@ovs Not in Python 2.

@mypetlion It does. // is floor division in both Python 2 and 3. 3**.5//1 evaluates to 1.0 in both versions.

@ovs You are correct. I mainly use Python 3. I had thought that the // operator was introduced in 3.0, but I looked it up and it was actually introduced in 2.2.

R, 51 50 bytes
f=function(x,y=x^.5%/%1)"if"(x,y^2+4*y+f(x-y^2),0)

Try it online!
A square of side length \$y\$ must have exactly \$y^2+4y\$ shields. We reduce by the largest square less than or equal to \$x\$ until \$x\$ is zero, accumulating the number of shields as we go.
Proof:
Given a perfect square of side length \$y\$, we need precisely 1 shield for each member of the square. Next, for each member on the edge, we need an additional shield. There are \$(y-2)^2\$ members not on the edges, so there are \$y^2-(y-2)^2\$ members on the edges. Finally, for each corner, we need an additional shield. Apart from the case where \$y=1\$, we can thus add 4. This simplifies to \$y^2+4y\$ which fortunately also yields the correct value of \$5\$ when \$y=1\$, allowing us to use it for all \$y\$.

You can simplify the explenation a lot: every roof square needs to be covered: $y^2$, and every side square needs to covered $4\cdot y$. Now it's obvious that it also works in the single-soldier case.

@ToddSewell sure, that's Arnauld's explanation, and it is far more elegant, but this is the way I approached it, so I'm sticking to it! Luckily, this is not a proof-golf question.

JavaScript (ES7), 34 bytes
f=n=>n&&(w=n**.5|0)*w+w*4+f(n-w*w)

Try it online!
How?
At each iteration, we compute the width \$w = \lfloor\sqrt{n}\rfloor\$ of the largest possible square. The number of shields \$s_w\$ for this square is given by:
$$s_w = w^2+4w$$
For instance, for \$w=3\$:
$$\begin{align}&\pmatrix{3 & 2 & 3\\2 & 1 & 2\\3 & 2 & 3}=&(s_3=21)\\&\pmatrix{1 & 1 & 1\\1 & 1 & 1\\1 & 1 & 1}+&(3^²=9)\\&\pmatrix{1 & 1 & 1\\0 & 0 & 0\\0 & 0 & 0}+\pmatrix{0 & 0 & 1\\0 & 0 & 1\\0 & 0 & 1}+\pmatrix{0 & 0 & 0\\0 & 0 & 0\\1 & 1 & 1}+\pmatrix{1 & 0 & 0\\1 & 0 & 0\\1 & 0 & 0}&(4\times3=12)\end{align}$$
The formula holds for \$w=1\$, as \$s_1=5\$.

Jelly, 13 bytes
Æ½²ạƊƬ_Ɲ½ẋ4S+

Try it online!
-1 thanks to Jonathan Allan.

Julia 0.6, 36 bytes
!n=(s=isqrt(n))*s+4s+(n>0&&!(n-s*s))

Try it online!
Uses the same \$ n^2 + 4n \$ method as @Giuseppe's R answer, though my method to arrive there involved less meaningful thinking and more just visual inspection: the inner square of 1s has dimensions \$ (n - 2) \$ by \$ (n - 2) \$, so that has \$ (n - 2)^2 \$ shields. Surrounding that, there are 4 walls of \$ n - 2 \$ soldiers each, each with 2 shields - so that adds \$ 4*(n - 2)*2 \$ shields. Finally, there are four 3s in the four corners, so that adds 12 shields.
$$ (n-2)^2 + 4*(n-2)*2 + 4*3 = n^2 + 4 - 4n + 8n - 16 + 12 = n^2 + 4n  $$
Ungolfed:
!n = begin       # Assign to ! operator to save bytes on function parantheses
  s = isqrt(n)   # Integer square root: the largest integer m such that m*m <= n
  s * s +
    4 * s +
      (n > 0 &&  # evaluates to false = 0 when n = 0, otherwise recurses
        !(n - s * s))
end

(This can also be done it in 35 bytes with n>0?(s=isqrt(n))*s+4s+f(n-s*s):0, but I wrote this for Julia 0.7 wanted to avoid the new deprecation warnings (requiring spaces are ? and :).)

Another overcomplicated explanation for the shield count, see my comment on @Giuseppe's answer.

@ToddSewell Yeah, area + perimeter is a more elegant way to look at it. I didn't do it that way though, and similar to Giuseppe my intention is to describe my approach than to give the neatest proof of the formula.

Stax, 15 bytes
ëñ|^○╖?║<l╛P╝z√

Run and debug it

Brachylog, 26 bytes
0|⟧^₂ᵐ∋N&;N-ℕ↰R∧N√ȧ×₄;N,R+

Try it online!
0           % The output is 0 if input is 0
|           % Otherwise,
⟧           % Form decreasing range from input I to 0
^₂ᵐ         % Get the squares of each of those numbers
∋N          % There is a number N in that list
&;N-ℕ       % With I - N being a natural number >= 0 i.e. N <= I
            % Since we formed a decreasing range, this will find the largest such number
↰           % Call this predicate recursively with that difference I - N as the input
R           % Let the result of that be R
∧N√ȧ        % Get the positive square root of N
×₄          % Multiply by 4
;N,R+       % Add N and R to that
            % The result is the (implicit) output

Retina 0.8.2, 28 bytes
.+
$*
(\G1|11\1)+
$&11$1$1
.

Try it online! Link includes test cases. Explanation:
.+
$*

Convert to decimal.
(\G1|11\1)+

Match odd numbers. The first pass through the group, \1 doesn't exist yet, so only \G1 can match, which matches 1. Subsequent matches can't match \G1 since \G only matches at the beginning of the match, so instead we have to match the 11\1 which is 2 more than the previous match. We match as many odd numbers as we can, and the total match is therefore a square number, while the last capture is one less than twice its side.
$&11$1$1

Add the side shields to each match. $& is \$n^2\$ and $1 is \$2n-1\$ while we need \$n^2+4n=n^2+2+2(2n-1)\$.
.

Sum and convert to decimal.

05AB1E, 17 bytes
[Ð_#tïÐns4*+Šn-}O

Try it online or verify all test cases.
Work-around because ΔDtïÐns4*+Šn-}O (15 bytes) doesn't seem to work.. Try it online in debug-mode to see what I mean. I would expect it to go from [45,'35',25] to [45,10] after the - and next iteration of Δ, but apparently it clears the stack except for the last value and becomes [10], resulting in 0 at the very end.. Not sure if this is intended behavior or a bug.. (EDIT: It's intended, see bottom.)
Explanation:
Also uses \$w^2+4w\$ where \$w\$ is the width in a loop like most other answers.
[        }     # Start an infinite loop:
 Ð             #  Triplicate the value at the top of the stack
  _#           #  If the top is 0: break the infinite loop
 t             #  Take the square-root of the value
               #   i.e. 35 → 5.916...
  ï            #  Remove any digits by casting it to an integer, so we have our width
               #   i.e. 5.916... → 5
   Ð           #  Triplicate that width
    n          #  Take the square of it
               #   i.e. 5 → 25
     s         #  Swap so the width is at the top again
      4*       #  Multiply the width by 4
               #   i.e. 5 → 20
        +      #  And sum them together
               #   i.e. 25 + 20 → 45
 Š             #  Triple-swap so the calculated value for the current width
               #  is now at the back of the stack
               #   i.e. [35,5,45] → [45,35,5]
  n            #  Take the square of the width again
               #   5 → 25
   -           #  Subtract the square of the width from the value for the next iteration
               #   i.e. 35 - 25 → 10
          O    # Take the sum of the stack
               #   i.e. [45,21,5,0,0] → 71

EDIT: Apparently the behavior I described above for Δ is intended. Here two 17-bytes alternatives provided by @Mr.Xcoder that do use Δ by putting values in the global_array (with ^) and retrieving them again afterwards (with ¯):
ΔÐˆtïnα}¯¥ÄDt··+O

Try it online or verify all test cases.
ΔÐˆtïnα}¯¥ÄtD4+*O

Try it online or verify all test cases.

dc, 25 bytes
d[dvddSa*-d0<MLa+]dsMx4*+

Try it online!
Calculates the shields as sum(n^2) (the original number) plus 4*sum(n) by pushing a copy of each square side length into stack register a as it goes, then adding all the values from register a as the recursion "unrolls".

Husk, 17 bytes
ṁS+o*4√Ẋ≠U¡S≠(□⌊√

Try it online!
Alternative
ṁS*+4m√Ẋ≠U¡S≠(□⌊√

Try it online!

APL (Dyalog Unicode), 31 30 bytes
{⍵<2:⍵×5⋄(S×S+4)+∇⍵-×⍨S←⌊⍵*.5}

Try it online!
-1 byte thanks to @jslip

0.5 -> .5 for 1 byte

Wow, how did I miss that

Ruby, 45 bytes
->n{n+(1..n).sum{n-=(z=(n**0.5).to_i)*z;z*4}}

Try it online!

Pyth, 19 bytes
A recursive function, which should be called using y (see the link).
L&b+*Ks@b2+4Ky-b^K2

Try it here!
Pyth, 21 bytes
The revision history is quite funny, but make sure to visit it if you want a much faster version :)
sm*d+4deeDsI#I#@RL2./

Try it here!
Explanation

sm*d+4deeDsI#I#@RL2./     Full program, let's call the input Q.
                   ./     Integer partitions of Q. Yields all combinations of positive
                          integers that add up to Q.
               @RL2       Take the square root of all integers of each partition.
             I#           Keep only those partitions that are invariant under:
          sI#             Discarding all non-integers. This basically only keeps the
                          partitions that are formed fully of perfect squares, but
                          instead of having the squares themselves, we have their roots.
       eeD                Get the partition (say P) with the highest maximum.
 m                        For each d in P ...
  *d+4d                   ... Yield d*(d+4)=d^2+4d, the formula used in all answers.
s                         Sum the results of this mapping and implicitly output.

PHP, 67 bytes
<?for($n=$argv[1];$w=(int)sqrt($n);$n-=$w**2)$a+=$w**2+$w*4;echo$a;

To run it:
php -n <filename> <n>

Example:
php -n roman_army_shields.php 35

Or Try it online!

Using -R option, this version is 60 bytes:
for(;$w=(int)sqrt($argn);$argn-=$w**2)$a+=$w**2+$w*4;echo$a;

Example:
echo 35 | php -nR "for(;$w=(int)sqrt($argn);$argn-=$w**2)$a+=$w**2+$w*4;echo$a;"

(on Linux, replace " with ')

Note: This is using Arnauld's answer great formula, I was not able to find anything shorter than that.

Swift 4, 111 99 84 78 bytes
func f(_ x:Int)->Int{var y=x;while y*y>x{y-=1};return x>0 ?(y+4)*y+f(x-y*y):0}

Try it online!
That feel when implementing integer square root manually is far shorter than the built-in...
Ungolfed and Explained
// Define a function f that takes an integer, x, and returns another integer
// "_" is used here to make the parameter anonymous (f(x:...) -> f(...))
func f(_ x: Int) -> Int {

    // Assign a variable y to the value of x

    var y = x

    // While y squared is higher than x, decrement y.

    while y * y > x {
        y -= 1
    }

    // If x > 0, return (y + 4) * y + f(x - y * y), else 0.

    return x > 0 ? (y + 4) * y + f(x - y * y) : 0
}


text:
Python: shortest way to interleave items from two lists
I'm trying to get the shortest way (character possible) to obtain List 3.
List 1 and List 2 are already given to me as arguments and are the same length.
l1 = [1, 2, 3, 4, 5]
l2 = ['a', 'b', 'c', 'd', 'e']

And List 3 should look like (yes, it needs to be a list):
l3 = ['a', 1, 'b', 2, 'c', 3, 'd', 4, 'e', 5]

Is your goal to literally output the specific list l3 = ['a', 1, 'b', 2, 'c', 3, 'd', 4, 'e', 5] given l1 = [1, 2, 3, 4, 5] and l2 = ['a', 'b', 'c', 'd', 'e'] already assigned, or is the idea that l1 and l2 could be any two lists of the same length?

Zip and Sum
[*sum(zip(l2,l1),())]

Try it online!
Zips the two lists together then adds all the tuples to make one combined list. The zip only works if the lists are guaranteed to be the same size, otherwise it truncates the longer list.
Added the surrounding [*  ] to transform it into a list as FryAmTheEggman suggests.

If using Python 2, you can just use list instead of [* (...) ] for +3 bytes.

Slice assignment
c=a*2
c[1::2]=a
c[::2]=b

This is three bytes longer than using Jo King’s solution c=[*sum(zip(b,a),())], but it’s nifty. It might be shorter situationally (I can’t think of where, though).


text:
Map an array of functions to their return values in point-free style
Introduction
I have some JavaScript code that uses Array.prototype.map to map an array of functions fns to their return values:

const fns = [() => 1, () => 2];
const result = fns.map(
  fn => fn()
);
console.log(result); // => [1, 2]

Challenge
The argument to map above is fn => fn(). The challenge is to rewrite this function using point-free style. Your solution should work when it replaces the third line of the above program:
const fns = [() => 1, () => 2];
const result = fns.map(
  /* your solution should work when inserted here */
);
console.log(result); // => [1, 2]

fn => fn() is not a valid solution because it defines a parameter named fn. Writing a function in point-free style requires writing it without any variable or parameter names.
Note that map will pass three arguments to your solution function: currentValue: () => T, index: number, and array: Array<() => T>. The function for the solution must return the result of calling the currentValue function, so hard-coding 1 and 2 will not help. The functions being mapped over are guaranteed to ignore their arguments and their this value, so calling the function in any way will work.
Scoring
The best answer is the one that is represented by the fewest tokens when lexed. The ANTLR 4 JavaScript lexer is the official lexer for the sake of objectivity, but if you know how a lexer works you should be able to estimate how many tokens some JavaScript needs without having to read that link. For example, fn => fn() is composed of five tokens: fn => fn ( ).
However, I personally think that figuring out any answer is the fun part, so if this problem interests you, try to solve it yourself before scrolling down and seeing the answer.

Based on the answer by Rory O'Kane:

10 tokens: Number.call.bind(String.call)

Try it online!
It is trivial, since Number.call, String.call, Object.call, Function.call, (function () {}).call, Function.prototype.call are all the same.
If Bind Operator Proposal is accepted, this could be simplified to:

6 tokens: ::Function.call.call

Babel
BTW, if eval is allowed eval("Number.call.bind(String.call)") only use 4 tokens.

This combination of Function.prototype.call and Function.prototype.bind works:
Function.prototype.call.call.bind(Function.prototype.call)

16 tokens: Function . prototype . call . call . bind ( Function . prototype . call )

const fns = [() => 1, () => 2];
const result = fns.map(
  Function.prototype.call.call.bind(Function.prototype.call)
);
console.log(result); // => [1, 2]

Explanation
Function.prototype.call is not a solution on its own because map will call call with its this value set to undefined. call’s purpose is to call the function in this, so when this is undefined a TypeError is raised.
Similarly, Function.prototype.call.bind(Function.prototype) is insufficient because the call function is called with this set to Function.prototype, and the function you want called set to the first argument. Calling Function.prototype() with any arguments returns undefined, so the function will return undefined instead of 1 or 2.
My solution works by using the second call to make the fn argument the this of the first call, like this:
fn => Function.prototype.call.call(fn)

Now the first call can do what it is made for, calling the argument in its this value.