text:
Organise the Gregorian Church's Music
The year is 930, and the Gregorian Church is having a problem. They have thousands of pages of chant music, but the problem is that all the sheet music was simply thrown onto a pile instead of having any real organisation system:

Image by user gamerprinter at Cartographers' Guild.
The Church needs to organise all the sheet music, so they have hired a medieval software engineer to write a program to organise it for them. You are the software engineer that has been hired. However, the compilation process in medieval times involves the program being written onto paper by a team of slow biblical scribes. To decrease the time it takes for the team of scribes to compile your code, you must make the program as small as possible.
The Church wants the chant music to be organised based off the musical scale they are written in. All of the Church's chant music is written in Dorian scales. Given the notes of a certain piece of music, your program will output the Dorian scale that it is in. Here, I will explain exactly what a Dorian scale is. If you already know, you may skip this section.
There are 12 possible notes in any melody. Here they are in order:
C C# D D# E F F# G G# A A# B

A semitone (represented using a S) is incrementing one step to the right, wrapping around (so a semitone up from B would be back to C). A tone (represented using a T) is two semitones. For instance, a semitone up from F# would be G. A tone up from F# would be G#.
To create a Dorian scale, we start from any note in the list, and then move up in the following pattern, listing the notes that we encounter:
T, S, T, T, T, S

An example. I start from A. The notes of my Dorian scale becomes:
A
B  (up a tone)
C  (up a semitone)
D  (up a tone)
E  (up a tone)
F# (up a tone)
G  (up a semitone)

The scale has the notes A, B, C, D, E, F#, and G. Because I started from A, we will call this the Dorian scale in A. There are therefore 12 different Dorian scales, each of which are named after the note that they started from. Each of them use the same pattern of tones and semitones, just starting from a different position. If my explanation is not coherent you may also consult Wikipedia.
The input of the program can be given from whatever is appropriate for your program (e.g. STDIN, command line argument, raw_input()). It may be not pre-initialised in a variable. The input will be a list of comma seperated notes, representing the melody of the piece. There may be repeated notes. There will always be enough different notes in the input to be able to decisively deduce the scale of the piece. An example input:
B,B,D,E,D,B,A,G#,A,G#,E,D,F#,E,F#,E,F#,G#,A

The output of the program should be the string Dorian scale in X, where X is the starting note of the scale. The output of the example input:
Dorian scale in B

Comparing this with the Dorian scale in B (B C# D E F# G# A) we see that all the notes of the melody are within this scale. The note C# is unused in this case. However there are sufficient notes to unambiguously identify B Dorian as the correct key. No other Dorian scale fits, because whatever other scale we try, there is always at least one note of the melody that does not belong to the scale.
This is code golf, so the entry with the shortest number of characters wins. Ask in the comments if you have questions.

So, what we should do is to only interpret the first tone/semitone?

@avall I'm sorry, I don't understand your question. The input won't always start with the tonic, if that's what you're asking.

Please provide us more examples. Especially those, which don't start with the tonic.

@avall C#,D#,A,B,A,F#,E ==> Dorian scale in F#

@avall F,A,C,B,E ==> Dorian scale in D

I still don't understand how the sequence of notes could even hint at the scale. F, A are two tones apart. B, E are 2.5 tones apart in one direction, 3.5 in the other one. Should we assume the tone never changes by more than 5 semitones, spans exactly 12 semitones, and output the lowest of them?

@JanDvorak We know that there are 12 dorian scales, the notes of which may be obtained using the method described in the question. The only Dorian scale that contains the notes F, A, C, B, E within it is the one that starts from D. I have a feeling I wasn't clear at all in my explanation.

The inverse problem is Scale from key and mode

I see nothing unclear about this question. For interest, the min number of notes needed to define a scale unambiguously is 3. For D Dorian B,F and either C or E suffice. On the other hand it's possible to give 6 notes and still be ambiguous: C,G,D,A,E,B could be either D or A dorian, depending if the F is natural or sharp. @VonIlya, what's the flaw you refer to? I notice if you name all scales as sharps you get into some horrible double-sharp situations, but non-musicians will just use the corresponding natural and not notice a problem. I'm willing to vote to reopen and help if you explain.

Sounds like a problem with your generator, not the question. Both examples in your comments have a tritone in them (B-F and A-D#) and a semitone in them, either of which on its own is sufficient to narrow it down to 2 possibilities.  Some of these diagrams would really help: http://en.wikipedia.org/wiki/Pitch_constellation. If you delete your own negative comments I'll open vote and possibly edit.  Musically it's better to say Bb dorian than A# dorian (the latter contains E# B# and F## if written correctly) but it's best to stick with the sharps now. I guess B C C# is undefined behaviour

I suppose so. I've deleted the comments now.

Reopen vote cast. It's too late here for me to help you with an edit, but I may do so tomorrow.

@steveverrill, I think the flaw is that this is modern Dorian, not mediaeval.

@Peter Taylor Hmm, that's true as well. Although I already threw historical accuracy out the window with the medieval software engineering part...

Can I use space separated list of notes as input?

@Ray Yes. aaaaaaa

By awarding a win so quickly, you discourage others from posting.  You also commit to an answer that may well not be the best (in this case, the shortest).

@David As per this meta question, I awarded the accept to the shortest answer after a waiting period of 12 days since I started the challenge. It just happened the CJam answer was posted right when I was going to accept the next shortest one.

@David Also, I considered not giving accepts for any of my questions, but I would think that would also discourage people from posting ("have you heard of that Ilya person that doesn't give +15 accepts out...?") Waiting for 12 days to let posts come in before accepting seemed like the best solution.

CJam - 61
C,q',/f{"FCGDAEB"_5<'#f++:s@m<7<:A-!{"Dorian scale in "A3=}*}

Try it at http://cjam.aditsu.net/

Wow, this must be my quickest win.. less than 1 minute :)

C, 171 146
i,b;main(int c,char**v){for(;c=v[1][i];)b|=c/65<<c*2%7+v[1][++i]%2*7;for(i=12;i--;)b&(1016056>>i)||printf("Dorian scale in %c%c",65+i*3%7,(i<5)*35);}

Parsing strings in C is not that easy, so I went for a more mathematical approach.
I take advantage of the Circle of Fifths. If we arrange the notes in the following order based on counting up 7 semitones at a time (known as a "fifth"), we find that all the notes permitted in any given scale form a consecutive block of 7 notes and all the prohibited notes form a consecutive block of 5 notes.
F C G D A E B F# C# G# D# A#

(it's a circle, it wraps back around to F at the end.)
The position of a natural note in the above sequence can be calculated as (ASCII code) * 2 % 7. Then if the next character is odd (applies to # but not comma, space or zero byte) we add 7 to make it sharp. We store a bitmap of the notes that have been used.
The number 243 (binary 11111000) corresponds to the notes prohibited in the scale of A# Dorian. I multiplied this by (1<<12)+1=4097 to give the magic number 1016056. This is rightshifted to check (by ANDing) if the melody contains prohibited notes for each of the 12 scales in turn. If the melody does not contain prohibited notes, the scale is printed.
For the output we need to print the scale name encoded in the reverse order to cycle of fifths above, remember we are going backwards because we are rightshifting.) The ASCII sequence ADGCFBEADGCF is generated by 65+i*3%7. For the first five of these a sharp must also be printed.
Ungolfed code
i,b;
main(int c,char**v){
  for(;c=v[1][i];)                          //for each character in first commanline argument v[1]
                                               //if it is a letter (assume uppercase, ASCII 65 or over)
   b|=c/65<<c*2%7+v[1][++i]%2*7;               //convert to position in the circle of fifths.
                                               //Add 7 if the next character is odd (ASCII'#')
                                               //leftshift 1 by this number and OR this with the contents of b.

  for(i=12;i--;)b&(1016056>>i)||printf         //if melody includes no prohibited notes for the scale i, print
   ("Dorian scale in %c%c",65+i*3%7,(i<5)*35); //the scale letter, and a # (ASCII 35) if required, otherwise an ASCII 0.
}

Invalid input behaviour: If insufficient notes are supplied to unambiguously determine the scale, it will output all possible scales. If an impossible combination of notes is supplied, it will output nothing. Notes must be delimited by a comma (or other non-whitespace character with an even ASCII code <= 64.) Spaces cannot be used as everything after the first space would be considered a different argument. ASCII codes >64 will be interpreted as notes in the manner described.

It shocked me that the circle of fifths has this property! Maybe I can use it to golf a bit more.

@Ray This is actually why we have the set of notes that we have. The octave has a frequency ratio 2:1. The fifth as defined by Pythagoras has a ratio of 3:2 and is the most important musical interval after the octave. Because 1.5^12 is close to but not equal to 2^7, the modern equal tempered fifth is squeezed down to 1.4983 so that exactly 12 fifths fit in 7 octaves. The old fashioned solution was to only use 7 notes out of the available 12 from the circle. That's why we have a scale based on 7 unevenly spaced notes. It's not some random convention, there's some solid maths behind it.

There are a number of instruments that arrange notes in fifths for convenience reasons (the violin is tuned in this way, and the bass guitar is tuned in fourths, which is a ratio of 4:3). The most striking example (and the only instrument I know of that has notes layed out in a circle of fifths for good acoustic design) is the steelpan: http://www.google.es/patents/US7696421 . With this layout it doesn't matter if the note next to the one you are hitting rings a bit.

Haskell - 152
w=words
n=w"C C# D D# E F F# G G# A A# B"
f s="Dorian scale in "++[n!!i|i<-[0..11],all(`elem`[(n++n)!!(i+j)|j<-[0,2,3,5,7,9,10]])s]!!0
main=interact$f.w

Ungolfed
type Note = String
type Scale = [Note]

notes :: [Note]
notes = words "C C# D D# E F F# G G# A A# B"

isScale :: Scale -> [Note] -> Bool
isScale scale notes = all (`elem` scale) notes

takeScale :: Int -> Scale
takeScale i = [(notes ++ notes) !! (i + j) | j <- [0, 2, 3, 5, 7, 9, 10]]

findScale :: [Note] -> Note
findScale xs = head [notes !! i | i <- [0..11], isScale (takeScale i) xs]

main = interact (("Dorian scale in "++) . findScale . words)

Haskell - 140
Make use of the Circle of Fifths property introduced by @steveverrill.
If we let circle0 = words "C G D A E B F# C# G# D# A# F" and circle = circle0 ++ circle0, then we can construct all scales by taking consecutive 7 notes in circle.
scales = [take 7 . drop i $ circle | i <- [0..11]]

In each scale constructed by this way, scale !! 3, the 4th element is the scale name.
Code
w=words
n=w"C G D A E B F# C# G# D# A# F"
f s="Dorian scale in "++[x!!3|x<-[take 7.drop i$n++n|i<-[0..]],all(`elem`x)s]!!0
main=interact$f.w

Ungolfed
type Note = String
type Scale = [Note]

notes :: [Note]
notes = words "C G D A E B F# C# G# D# A# F"

scales :: [Scale]
scales = [take 7 . drop i $ notes ++ notes | i <- [0..11]]

findScale :: [Note] -> Note
findScale xs = head [scale !! 3 | scale <- scales, all (`elem` scale) xs]

main = interact (("Dorian scale in "++) . findScale . words)

Python 2 - 177 characters
It's not that short, but I find it the joy of Python to write multiple nested for loops in one line, even when not golfing. Unfortunately, I had to put the input statement on a separate line so that it would not execute more than once.
j=set(raw_input().split(','))
print"Dorian Scale in",[x for x in[["A A# B C C# D D# E F F# G G#".split()[(b+n)%12]for n in[0,2,3,5,7,9,10]]for b in range(12)]if j<set(x)][0][0]

I don't use Python 3, but I believe this is a rare instance when the print statement would not need more characters. Since print is a function there, I would be able to offset the need for parentheses with the use of the * list unpacking operator to replace the last [0].

You'd also be able to substitute input for raw_input and save 4 characters in Python 3.

"I find it the joy of Python to write multiple nested for loops in one line": but do you find joy in reading them?

@Wideshanks Of course not... it's all about the write-only code!

Ruby - 132
12.times{|i|$*[0].split(?,)-(g=(0..6).map{|j|%w{C C# D D# E F F# G G# A A# B}[-i+=~(58>>j&1)]})==[]?(puts"Dorain scale in "+g[0]):g}

Input from command line args.
e.g. ruby dorianscale.rb B,B,D,E,D,B,A,G#,A,G#,E,D,F#,E,F#,E,F#,G#,A
Try it at: ideone

Scala, 130 128 127
print("Dorian scale in "+(".#?".r findAllIn "FCGDAEBF#C#G#D#A#"*2 sliding(7)find{l=>args(0)split','forall(l contains _)}get 3))

Using the circle of fifths method.
Input from command line args ie
scala dorianscale.scala B,B,D,E,D,B,A,G#,A,G#,E,D,F#,E,F#,E,F#,G#,A

authors: ملك العالم دي


text:
Display a tally (in varying bases)
Tallying is a simple counting system that works in base 5. There are various different tallying systems used around the world, but the one that is used in most English-speaking countries is perhaps the most simple - count units by marking vertical lines, then for each 5th mark put a horizontal line through the previous collection of four. This clusters the tally marks in groups of 5 (and makes them easier to quickly count).
You are going to write a program that displays tally marks up to a given value. But, tallying in only base 5 is boring! Therefore, your program should also be able to display tallies in different bases.
Input
The input will be either one or two non-negative integer values separated by a comma (e.g. 9 or 8,4). The first number is the value that should be displayed by the tally. The second value is the base of the tally. If the second value is not given, use base 5.
Output
The output will be the inputted value represented as ASCII art tally marks. Here are some examples you can test your program against - your output should match them exactly!
Input: 12 or 12,5
 | | | |   | | | |   | |
-+-+-+-+- -+-+-+-+-  | |
 | | | |   | | | |   | |

Input: 7,3
 | |   | |   |
-+-+- -+-+-  |
 | |   | |   |

Input: 4,2
 |   |
-+- -+-
 |   |

Input: 6,1 or 6,10 (notice the leading spaces)
 | | | | | |
 | | | | | |
 | | | | | |

Note also that base 1 is intended to be inconsistent - only vertical lines should be used.
If either of the inputted values is 0, there should be no output whatsoever (and your program should end gracefully).
Rules

This is code-golf, so the shortest correct implementation (in bytes) wins.
Input/output can be in any suitable medium (e.g. stdin/stdout, file...).
Input can be in the form of multiple command-line arguments or separated by spaces, etc. if it is more suitable for your target language.
Trailing newlines are allowed in the output. Trailing spaces are not. This rule only applies when there is an output (i.e. not when the inputted value is 0).
Your code must default to base 5 when no base is input.

Shouldn't the output of 6,1 look more like -+- -+- -+- -+- -+- -+-?

If you state "The input will be either one or two positive integer values separated by a comma (e.g. 9 or 8,4)." then we should be able to take that as a given, and not have to worry about "Your program should be robust - you should validate the input..." beyond handling one or two numbers.

@PeterTaylor -+- would represent two, because there's a vertical line and a horizontal score through it. Base 1 would only have vertical lines. @AndoDaan ammended.

Ok, --- --- --- --- --- --- then. For consistency with the other bases you should be putting a horizontal strike through b-1 vertical lines. If it's intended to be inconsistent you should state that explicitly.

I've done that. Sorry, I thought it was implied.

is there any leeway in the input format (comma-separated values are much less helpful than two separate command-line arguments, or even just space-separated standard input)?

Yes, I'll add this to the rules.

Are trailing newlines allowed?

Yes, added. I need to find more ways of surpassing the 15 character minimum...

But are trailing newlines allowed if n==0? Or does the "n=0->no-output" rule overrule the trailing-newline rule?

The no output rule overrides it. Ideally your program will spot that n = 0 and exit before any printing is done (or just skip it altogether).

Is there a maximum value for the numbers? Can I assume they're less than two billion?

I said "positive integer", so I guess the maximum depends on your implementation. I'm not evil enough to want to test any inputs that high though :^)

@ipi I was about to abuse a mistake you made when I decided I'd better correct your post instead. Zero is not "positive" yet it is a valid input, so I changed it to say "non-negative".

With regard to the "no trailing spaces" rule, does this forbid trailing spaces at the end each of the 3 lines of output, or am I missing the point completely?

If input is two numbers separated with a comma, like 7,2, can I implement this as receiving input between the parentheses of a function call like f(7,2)?

Can we assume 2¹⁵ - 1 as an upper limit for the numbers you test?

CJam 103 85 72 characters
Try it at http://cjam.aditsu.net/.
original
q","/(i:A\_,{~i}{;5}?:B_@*{(_{" |"*S"l"++AB/*AB%}{;MA}?\:J" |l""-+ "er\" |"*N+_J\+@2$+@J\+++"l"Ser}{;}?

Works by defining one set of tallys with spaces, lines and an l for spaces that should remain spaces.  Then takes advantage of er (tranliteration) function to make the second line.  Most inefficient part is dealing with the 1 and 0 special cases.  Will edit as I improve it.  Tip I took too long to realize: as the second input being 1 is the same as infinity or the first input +1, redefining it when it is equal to 1 saves alot of work.
most improved so far with comma delimited
l",":G/(i:A\_5a?~i:B_@*{(_" |":K*\{SG++AB/*AB%}{A}?\_KG+"-+ "er[\GSer_@@M]\K*N+*}{;}?

most improved so far with space delimited input
Naturally as CJam is really designed for space delimited input. Placing the input at 20 3  instead of 20,3 is a huge benefit.
ri:Aq_5s?S-i(_)A)?:B*{B(" |":K*STs++ABmd@@*_K"-+"er[\_@@M]\K*N+*TsSer}M?

Python 2 - 111 108 119 144 140 136 135 134 - Try it
Ok, let's give it a try:
i=input()
n,b=[(i,5),i][i>[]]
o=b-1
a=[n,n%b][b>1]*' |'
m=(b>1)*n/b
s=(' |'*o+'  ')*m+a
print(s+'\n'+('-+'*o+'- ')*m+a+'\n'+s)*(b*n>0)

Edit: I've overlooked that there should be no output if n==0 or b==0. This costs me 11 characters. :(
Edit: Ok, after fixing the second issue mentioned in the comments my solution basically converged to the one from BeetDemGuise.

This prints newlines when either of the inputs (or both) are zero which according the challenge is undesired. Also, what if only one number is input into the program?

This fails when the second value is omitted (b should be 5 in this case). I'll make it more clear in the question. Edit: oh, never mind, you fixed it just as I made this comment!

Which Python is this?

It's Python 2.7.8. - Oh, there was a tiny mistake at the very end...

If it's Python 2.x couldn't you save one more character by using n/binstead of n//b?

Hey, you're right! I always forget that Python does integer division by default, since the Spyder command line does not: 3/2 yields 1.5.

If you try this with large numbers then the result looks sloppy. Example

I believe this answer will leave trailing spaces for input "5".

@VisualMelon: No, I don't think so. You can try it here.

@G_Wilson: That behavior was not clearly specified and I guess every answer here has its problems for large numbers. For a sufficiently wide terminal window it'll work. ;)

@Falko IDEOne refuses to work for me, but I asked a friend to test it was printing 5 trailing spaces for input five (2 on the first line, one on the next, two on the last line (padded to the 2*n char, as such)). I may be mis-interpreted what the OP meant by trailing spaces, I'll ask him to clarify in a comment.

Bash, 239 228 199 189 188
Here's my attempt, it could be golfed a lot.
Note: the second line does not subtract 5 from 2, it sets a default value if $2 is empty!
n=$1
b=${2-5}
((n<1&b<1))&&exit
while ((n>b&b>1));do
n=$[n-b]
x+=\
y+=-
for i in `seq $[b-1]`;{
x+='| '
y+=+-
}
x+=\
y+=\
done
for j in `seq $n`;{
x+=' |'
y+=' |'
}
echo -e "$x\n$y\n$x"

Does {1..$n} work instead of \seq $n``?

@FUZxxl unfortunately not, h=8;echo {1..$h} outputs {1..8}

That's not good.

Python - 171 143
i=input();t,b=i if[0]<i else(i,5);b=[b,t+1][b==1];l,d,m,o=' |',t/b,t%b,b-1;r=(l*o+'  ')*d+l*m
if t*b>0:print r,'\n',('-+'*o+'- ')*d+l*m,'\n',r

The program is pretty straight-forward:

Get the input and try to unpack into t,b. If that fails, simply assign the correct values.
If the base was 1, change its value to something that can handle all vertical lines easily (t+1).
Set some variables and create the bottom and top sections of the tallies.
Print out the tallies if both t and b are non-zero.

EDIT 1: Use the input function instead of raw_input after some playing around.
EDIT 2: Thanks to Falko for pointing out a small bug with my non-zero checking. Now our code is basically identical, less some variable names and some small logic.
EDIT 3: Thanks to how Python compares sequences and different types, we can compare i to a list to get a shorter version of our try...except block.
Here is the ungolfed version:
i=input()

# If True, `i` must be a list
if [0]<i:
    t,b=i
# Otherwise, we know its a number (since `list` comes after `int` lexicographically.)
else:
    b=5
    t=i

b = b if b==1 else t+1
l=' |'
d=t/b
m=t%b
o=b-1

r=(l*o+'  ')*d+l*m
if t and b:
    print r,'\n',('-+'*o+'- ')*d+l*m,'\n',r

I think t&b is False for 10,5. Otherwise our solutions are converging! ;)

@Falko You are right on both counts! You know what they say about great minds.

It'd be really great if we could find a short way to test if i is scalar or a list. Then we could drop the try ... except monster.

@Falko I think I found a 1byte-better check. A list is always greater than an int. Also, lists are compared in lexicographical order. So if we compare [0]<i this will always return False if i is a number and True if i is a list (with a non-zero first element).

Great! I further shortened your approach. Nice teamwork! :)

I have not been able to test this (can't get IDEOne to work and I don't have Python 2) but it would appear to me that this will print a trailing space in the 2nd line if it ends "- ", am I missing something?

C - 193
I'm so sorry. Dealing with the special case for 1 was a bit of a bad hack so I guess this could be golfed more with a better approach. Also, this code includes a new line at the beginning of the output, so if this is not allowed, please let me know.
Of course, very ugly-looking defines always help :)
Character count includes only necessary spaces and new lines.
#define P printf(
#define L P" |")
#define A P"\n");for(i=0;i<a;)b==1?i++,L:i++&&i%b==0?P
i;
main(a,b)
{
    scanf("%d,%d",&a,&b)<2?b=5:!b?a=0:a;
    if(a){
    A"  "):L;
    A"- "):a%b&&i>a/b*b?L:P"-+");
    A"  "):L;}
}

Your code seems to print newlines when one of the values is zero. This is explictly disallowed. Your solution is not conforming.

@FUZxxl You're right, I missed that! This bad quick fix will have to do for now. I hope I have time soon to find a better way.

I'm pretty sure you can save a few characters by replacing printf with puts, and replacing return with a ternary operator.

@millinon The problem with puts is that it adds a new line every time :(. And for the ternary operator, it is not possible to add returns or fors inside them!. Your comment did give me the idea to save a few more characters very easily by removing the return though. Thanks!

Java, 343
class C{public static void main(String[]a){long n=new Long(a[0])+1,b=a.length>1?new Long(a[1]):5;if(b>0){if(b<2)b=(int)2e9;int i;for(i=1;i<n;i++)p(i%b>0?" |":"  ");p("\n");for(i=1;i<n-n%b;i++)p(i%b>0?"-+":"- ");if(n>b)p("- ");for(i=1;i<n%b;i++)p(" |");p("\n");for(i=1;i<n;i++)p(i%b>0?" |":"  ");}}static void p(String s){System.out.print(s);}}

Less golfed:
class C {
  public static void main(String[] a) {
    long n=new Long(a[0])+1, b=a.length>1 ? new Long(a[1]) : 5;
    if(b>0) {
      if(b<2) b=(int)2e9; // if the base is 1, pretend the base is 2 billion
      int i;
      for(i=1;i<n;i++) p(i%b>0 ? " |" : "  ");
      p("\n");
      for(i=1;i<n-n%b;i++) p(i%b>0 ? "-+" : "- ");
      if(n>b) p("- ");
      for(i=1;i<n%b;i++) p(" |");
      p("\n");
      for(i=1;i<n;i++) p(i%b>0 ? " |" : "  ");
    }
  }
  static void p(String s) {
    System.out.print(s);
  }
}

You can save a few by making i a long so you don't have to declare it separately. A few more by doing i++%b>0 in your loops instead of incrementing it separately (and i++<n%b in the third loop). Another one by using b=b<2?(int)2e9:b.

Perl - 167 165 156
my($n,$b)=($ARGV[0]=~/(\d+)(?:,(\d+))?/,5);print$b>1?map{join(" ",($_ x($b-1))x int($1/$b)," | "x($1%$b))."\n"}(" | ","-+-"," | "):join" ",("---")x$1if$1*$b

ungolfed
my($n,$b) = ($ARGV[0] =~ /(\d+)(?:,(\d+))?/, 5);
print($b>1 ?
    map{
        join(" ",($_ x ($b-1)) x int($1/$b)," | " x ($1%$b))."\n"
    } (" | ","-+-"," | ") :
    join " ", ("---") x $1
) if $1 * $b

displays horizontal lines instead of vertical ones for base 1 :(

@chineseperlgoth yes, that's one of the requirements. Please read comments on Q.

C# 271bytes
Not the shortest, I couldn't golf the input reading due to it needing to accept 0 as an input.
using C=System.Console;class P{static void Main(){var L=C.ReadLine().Split(',');int t=int.Parse(L[0]),f=L.Length>1?int.Parse(L[1]):5,r=3,i;for(var R="";t*f>0&r-->0;C.WriteLine(R.TrimEnd()))for(R="",i=0;i<t;R+=r==1&i++<t-t%f?(i%f<1?"- ":"-|"):i%f<1?"  ":" |")f+=f<2?t:0;}}

Formatted code:
using C=System.Console;

class P
{
    static void Main()
    {
        var L=C.ReadLine().Split(',');
        int t=int.Parse(L[0]),f=L.Length>1?int.Parse(L[1]):5,r=3,i;

        for(var R="";t*f>0&r-->0;C.WriteLine(R.TrimEnd()))
            for(R="",i=0;i<t;R+=r==1&i++<t-t%f?(i%f<1?"- ":"-|"):i%f<1?"  ":" |")
                f+=f<2?t:0;
    }
}

JavaScript (193)
This might be overly complex.
s=prompt().split(",");a=+s[0];b=s[1];b=b?+b:5;o=b>1;v=" | ";q=w="";for(g=~~(a/b),c=o?a-g:a;g+1;g--,q+=" ",w+=" ")for(i=o;c&&i<b;i++)c--,q+=v,w+=g&&o?"-+-":v;if(a&&b)console.log(q+'\n'+w+'\n'+q)

Commented version
s=prompt().split(",");
a=+s[0];
b=s[1];
b=b?+b:5;   // convert b to int and default to 5
o=b>1;      // special handling for b0 and b1
v=" | ";
q=w="";
// calculate number of lines and number of groups
for(g=~~(a/b),c=o?a-g:a;g+1;g--,q+=" ",w+=" ")
    for(i=o;c&&i<b;i++)
        c--,  // decrease line count
        q+=v,
        w+=g&&o?"-+-":v; // use " | " for last group and "-+-" for others
if(a&&b) // handle b0
    console.log(q+'\n'+w+'\n'+q)

Lua - 219 203 bytes
I went for the make d copies of b copies of "|", then add r copies of "|" at the end. I feel like maybe I should have gone with the 'tally up' the "|"s to the string one at a time.
l=' |'s=string.rep _,_,a,b=io.read():find'(%d+)%D*(%d*)'b=tonumber(b)or 5 d=(a-a%b)/b f=b>1 and s(s(l,b-1)..'  ',d)g=b>1 and s(s('-+',b-1)..'- ',d)r=b>1 and a%b or a e=s(l,r)..'\n'print(f..e..g..e..f..e)

ungolfed:
l=' |'          --the base string
s=string.rep    --string.rep will be used a lot, so best shorten it

_,_,a,b=io.read():find'(%d+)%D*(%d*)' --reads a,b I'm probably way of the mark with this one

b=tonumber(b)or 5

d=(a-a%b)/b -- shorter than math.floor(a/b), d equal the vertical mark

f=b>1 and s(s(l,b-1)..'  ',d) or '' --creates d multiples of b multiples of "|" more or less
g=b>1 and s(s('-+',b-1)..'- ',d)or''--same as above but with the middle "-+-"

r=b>1 and a%b or a --idk maybe i should set r before d(a- a%b )/b

e=s(l,r)..'\n'  -- makes the remainder string, notice that if b==1  then e will output all the "|"

print(f..e..g..e..f..e) -- here's where the real magic happens!

Sample:
c:\Programming\AnarchyGolfMine>lua test.lua
13,5
 | | | |   | | | |   | | |
-+-+-+-+- -+-+-+-+-  | | |
 | | | |   | | | |   | | |

c:\Programming\AnarchyGolfMine>lua test.lua
6,2
 |   |   |
-+- -+- -+-
 |   |   |

c:\Programming\AnarchyGolfMine>lua test.lua
18,1
 | | | | | | | | | | | | | | | | | |
 | | | | | | | | | | | | | | | | | |
 | | | | | | | | | | | | | | | | | |

Could you post a sligthly more readable and ungolfed version? Golfing in Lua looks interesting!

@Alessandro done. And thanks, it made find a couple things I missed.

Python - 127 123 122
Just sneaking in with a slightly shorter python version.
edit: Fixed 0 not printing nothing and rejigger, ended up the same length
k=input()
k=i,j=((k,5),k)[k>[]]
for m in[' |','-+',' |']*all(k):
 print(m*(j-1)+m[0]+' ')*(i/j*(j>1))+' |'*(i%(j+(j<2)*i))

C (207 characters)
The newline right before exit is for legibility only.
#define P printf(
#define t(v)for(a=c;b<=a;a-=b)a-c&&P" "),P v+1),q(b,v);q(a," |");P"\n");
q(n,c){while(n--)P c);}a;b;c;main(){scanf("%d,%d",&c,&b)<2?b=5:0;b&&c||
exit();b==1?b=32767:0;t("| ")t("+-")t("| ")}

scanf usage shamelessy stolen from Allbeert. Notice that this solution does not compile with gcc as it tries to enforce a nonexistant prototype for exit. Compile with a working C compiler like tcc. Also, this function may or may not work on 64 bit platforms. Use with care.
Here is the original ungolfed implementation this is based on:
#include <stdio.h>
#include <stdlib.h>

static void
tally_line(int base, int count, const char *str)
{
     int follower = 0, i;

     /* full tallies first */
     for (; count >= base; count -= base) {
          if (follower++)
               putchar(' ');

          /* only print second character */
          printf(str + 1);

          for (i = 0; i < base; i++)
               printf(str);
     }

     /* partial tally */
     for (i = 0; i < count; i++)
          printf(" |");

     /* newline */
     puts("");
}

extern int
main(int argc, char **argv)
{
     int base, count;

     /* do away with program name */
     count = atoi(*++argv);

     base = argc - 3 ? 5 : atoi(*++argv);

     /* remove 0 later */
     base | count || exit(0);

     /* a crossed-out tally never appears for large numbers */
     if (base == 1)
          base = 32767;

     tally_line(base, count, "| ");
     tally_line(base, count, "+-");
     tally_line(base, count, "| ");

     return (EXIT_SUCCESS);
}

Python 2, 134 126 123 114 bytes
lambda i,j=5,a=" |":"\n".join(("",(a*~-j+"  ","-+"*~-j+"- ")[x%2]*(i/j))[j>1]+a*(i,i%j)[j>1]for x in(0,1,2)if i*j)

Try it online!
Old question I know but fun to have a go at anyway. Chance to try out a few tricks I've learned since joining.

source: Stack Exchange

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

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

sort: votes


text:
Rosetta Stone Code Challenge
I presume you've all heard of the Rosetta Stone, an ancient stone found to have essentially the same passage written on it in three different scripts. This challenge is based upon that: you have to write three versions of the same program in different languages.
The three programs must output the first n iban numbers, n being a number input by the user. There are only 30,275 iban numbers, so if n is greater than 30275, the program should return an error.
The challenge of the Rosetta Stone was that the scripts didn't appear to be mutually intelligible–knowing one didn't automatically make the others understandable. Your three programs should similarly be mutually unintelligible. That is, you may not golf down a Python 2 program and then submit it (or a minor modification) as a Python 3 version too, nor a C program as C++, etc. To prevent this, the Levenshtein distance between any two versions should be at least 25% of the length of the shorter of the two versions being compared, and at least 16 as an absolute numerical value. You may check conformance using this online Levenshtein distance calculator.
The winner is the person with the shortest combination of programs.

I retagged the question. I replaced code-golf with code-challenge because your scoring is not purely by code size. I also removed the rosetta-stone tag. While your challenge is clearly inspired by the Rosetta Stone and is also about writing code in multiple languages, the rosetta-stone tag explicitly indicates that answers should be written in as many languages as possible which is not true for this challenge.

Upvotes+codelength? Highest score? do you really want huge bloated programs? Upvotes-codelength would be better. Also is that codelength for one program or all three?

@steveverrill it is -length

What should the output be if n > 30275?

The first time around, I read "iban number" as IBAN number, unfortunately.

On a separate issue, mixing objective criteria with popularity seems like a way to get the worst of both worlds. If a question has an objective criterion, it should be scored on that criterion and not on popularity.

Are there restrictions on using 3rd party libraries and such?

@Danny You can use whatever you want

I think you can save this problem by making the scoring strictly objective. The "popularity" scoring is usually a last resort for fun problems that are otherwise impossible to score.

Does C# and Java count as a valid combination? (I don't wanna start any arguments, just wondering)

Originally this was scored by "shortest longest program" of the three, now it just says "shortest program". May I suggest "shortest total length of the three programs"? "Shortest program" to me means golf it down in one language and the other two don't matter.

Why the downvotes? I actually think this one can be fun. It's a real rosetta stone challenge.

Also, "and so on..." is pretty vague. Unless you can give a full list of banned combinations, people are going to have to just hope their choices aren't banned together. For instance, you ban python 2/3, but don't mention java 6/7/8. I can assume that's banned, but what about Java/Groovy, or Javascript/Coffeescript?

Do we have to include the entire program? e.g. int main... or can we just include the good stuff?

@Geobits You can't expect me to list them all!

@Milo Yeah, exclude the required stuff

@BetaDecay What about banning the versions of the same language, and supersets (e.g. C++ and C or Objective-C and C), and each program has to differ by at least 10 characters (excluding variable names)?

@BetaDecay Without a clear list you're telling people to guess/hope what combinations are valid. Just in the comments so far, I've asked about two combinations, Milo has asked a couple, and you haven't answered either. So yea, I can expect you to list them all. Either that or find some better way to describe what makes a pair of languages banned (probably the better option).

@Geobits Hey, sorry, I haven't been online to reply. Anyway, I've edited the question to using Milo's suggestion of language families and difference of 10 characters.

I'm not sure how to interpret The winner is the person with the shortest program., given that every answer must contain three programs. If we just look at the shortest of the three, it doesn't make much sense to post the other two. Also, in what universe are Bash and Batch similar languages?

@Dennis They're vaguely similar... And about the winning criteria, that has become diluted and nonsensical over time due to suggestions from various people. It seemed alright at the time.

I've edited the question to provide a way of easily verifying conformance with the spirit of the question, but had to invent thresholds. I think they're reasonable but you may want to tweak them, @BetaDecay.

@comperendinous That's brilliant thanks, I'll leave it as it is

Im afraid there isnt much choice in strategy to generate the numbers and three required languages for each entry pretty much forces duplicates or few submissions.

@comperendinous adding the Levenshtein distance was a really nice effort but I fear it might not be thorough enough, just swapping the order of some things will easily do to get around any reasonable threshold.

When was this reopened?

424 425: Haskell, Python 2, Perl
As they should for a true Rosetta comparison, all three programs work the same way, taking input from the first command-line argument and building up the list with the same rules, and variable names, where possible.
Haskell, 171
import System.Environment
main=do i<-getArgs;putStr.show$[n|n<-[0..777777],all(`notElem`"5689").show$n,all(\d->n`div`d`mod`100`notElem`13:[30..39])[1,1000]]!!(read.head$i)

Python 2, 156
import sys
print[n for n in range(777778)if all([c not in"5689"for c in str(n)])and all([n/d%100not in[13]+range(30,40)for d in[1,1000]])][int(sys.argv[1])]

Perl, 97 98
$i=@ARGV[0];die if $i>30275;for(0..777777){push@n,$_ if!(/[5689]/ or/(13|3.)(|...)$/)}print@n[$i]

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


text:
Stack Exchange Stock Exchange ~ Revised
Background
You are all traders for a slightly less than reputable stock firm. You all are part of a group of traders who focus only on one specific stock.
Each hour each trader has a chance to Buy X stocks or Sell X stocks. There are 50 hours per round and 3 rounds per competition. At the end of all of the rounds the trader with the highest average value wins a trip to Jamaica!
Gameplay
There are 3 rounds of 50 turns each.
Each trader begins the round with $5000 and A random number of shares between 20 and 30 shares. The price of the shares starts at a random number between 10 and 150.
Each turn each trader can Buy any number of shares they can afford or Sell any number of shares they currently hold, each for the current price per share.
The price per share increases by a random number between 1 and 5 for each share bought and decreases by a random value between 2 and 6 for each share sold. The minimum price is $1.
It is important to note that all traders process their transactions at the same time, meaning that any trader buying/selling shares will not affect the price until the next turn.
The player with the highest average value at the end of the 3 rounds wins. Value is determined by taking the amount of money left over at the end of the round and adding the number of shares owned by the trader * closing market price.
Arguments
Your program will be rerun at the start of each turn receiving the current market price, the trader's current amount of money and the number of shares owned by that trader.
Ex:
120 5000 0

Output
Your trader program must output a letter corresponding to the action it would like to take followed by the quantity.
Ex:
B10 //Buy 10 shares

or
S3 //Sell 3 shares

The trader also has the option to not do anything that turn. That can be accomplished by outputting a W or any other command that is not 'B>amnt<' or 'S>amnt<'
Submissions
Your program will be inside a 'players/>your program name<' directory:
+-- players
|   +-- BotNameFolder
|       +-- BotProgram

Please provide your code along with a command line argument to run it from inside the 'players' directory.
For example the Test1 trader could be run with java -cp "Test1" Test1
Additional Rules
Go ahead, shoot yourself EmoWolf, Idc.
No messing with anything outside of your BotNameFolder directory, feel free to create files in there though for persistent info throughout rounds / turns.
Do not intentionally create programs to crash the simulation.
I will accept multiple entries per user, as long as the entries act as seperate entities (No insider trading).
Leaderboard
[java&-cp&"TestPlayer"&Test1]:$10027395221
[python&daydreamer/daydreamer.py]:$5000
[java&-cp&"DayTrader"&DayTrader]:$4713199930331196453

I will try to update the leaderboard at least once a day
Controller
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Random;

public class Controller {

    public static BigInteger marketValue = BigInteger.valueOf(100);
    public static BigInteger newValue = BigInteger.valueOf(100);

    public static final char BUY = 'B';
    public static final char SELL = 'S';

    public static final int MARKET_INDEX = 1;
    public static final int MONEY_INDEX = 2;
    public static final int SHARE_INDEX = 3;

    public static int numRunning = 0;
    public static final int MAX_RUNNING = 10;

    public static void main(String[] args){
        try {
            BufferedReader br1 = new BufferedReader(new InputStreamReader(new FileInputStream("resources/config")));

            int numRounds = Integer.parseInt(br1.readLine());
            int turnsPerRound = Integer.parseInt(br1.readLine());

            //Create the array of players
            List<String> players = new LinkedList<String>();
            String line1 = null;
            while((line1 = br1.readLine()) != null){
                players.add(line1);
            }
            BigInteger[] totalVals = new BigInteger[players.size()];
            for(int i = 0; i < totalVals.length; i++){
                totalVals[i] = BigInteger.valueOf(0);
            }
            br1.close();

            //Begin processing
            for(int round = 0; round < numRounds; round++){
                //Create players' shares and currency array
                Map<String,BigInteger[]> vals = new HashMap<String, BigInteger[]>();
                for(int i = 0; i < players.size(); i++){
                    vals.put(players.get(i), new BigInteger[]{BigInteger.valueOf(5000), BigInteger.valueOf(getRandInt(20,30))});
                }
                marketValue = BigInteger.valueOf(getRandInt(10,150));
                newValue = marketValue;
                for(int turn = 0; turn < turnsPerRound; turn++){
                    marketValue = newValue;
                    Queue<Object[]> processQueue = new LinkedList<Object[]>();
                    for(String playerKey : vals.keySet()){
                        BigInteger[] valSet = vals.get(playerKey);
                        String[] pkParts = playerKey.split("&");
                        String[] parts = new String[pkParts.length + 3];
                        for(int i = 0; i < pkParts.length; i++){
                            parts[i] = pkParts[i];
                        }
                        parts[pkParts.length] = marketValue + "";
                        parts[pkParts.length + 1] = valSet[0] + "";
                        parts[pkParts.length + 2] = valSet[1] + "";
                        processQueue.add(new Object[]{playerKey, parts});
                    }

                    while(!processQueue.isEmpty() || numRunning > 0){
                        if(numRunning < MAX_RUNNING && !processQueue.isEmpty()){
                            numRunning++;
                            Object[] o = processQueue.poll();
                            String pKey = (String)(o[0]);
                            String[] p = (String[])(o[1]);
                            try {
                                Process proc = new ProcessBuilder(p).directory(new File("resources/players").getAbsoluteFile()).start();
                                BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
                                String line = br.readLine();
                                br.close();
                                switch(line.charAt(0)){
                                case BUY :
                                    BigInteger numShares = new BigInteger(line.substring(1).trim());
                                    if(numShares.multiply(marketValue).compareTo(vals.get(pKey)[0]) <= 0){
                                        BigInteger[] tempVals = vals.get(pKey);
                                        tempVals[0] = tempVals[0].subtract(numShares.multiply(marketValue));
                                        tempVals[1] = tempVals[1].add(numShares);
                                        vals.put(pKey, tempVals);
                                        newValue = newValue.add(numShares.multiply(BigInteger.valueOf(getRandInt(0,2))));
                                        if(newValue.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) >= 1){
                                            newValue = BigInteger.valueOf(Integer.MAX_VALUE - 1);
                                        }
                                    }
                                    break;
                                case SELL:
                                    BigInteger shares = new BigInteger(line.substring(1).trim());
                                    if(shares.compareTo(vals.get(pKey)[1]) <= 0){
                                        BigInteger[] tempVals = vals.get(pKey);
                                        tempVals[0] = tempVals[0].add(shares.multiply(marketValue));
                                        tempVals[1] = tempVals[1].subtract(shares);
                                        vals.put(pKey, tempVals);
                                        newValue = newValue.subtract(shares.multiply(BigInteger.valueOf(getRandInt(5,10))));
                                        if(newValue.compareTo(BigInteger.valueOf(1)) <= -1){
                                            newValue = BigInteger.valueOf(1);
                                        }
                                    }
                                    break;
                                }
                            } catch (Exception e) {
                                System.err.println("[" + pKey + "] threw error:");
                                e.printStackTrace();
                            } finally{
                                numRunning--;
                            }
                        }else{
                            try{
                                Thread.sleep(50);
                                continue;
                            }catch(InterruptedException e){
                                continue;
                            }
                        }
                    }
                    System.out.println("Turn " + turn + " over: " + marketValue);
                }
                System.out.println("End of round market value is: " + marketValue);
                int count = 0;
                for(String player : vals.keySet()){
                    totalVals[count] = totalVals[count].add(vals.get(player)[0].add(vals.get(player)[1].multiply(marketValue)));
                    count++;
                }
                newValue = BigInteger.valueOf(100);
            }
            for(int i = 0; i < players.size(); i++){
                System.out.println("[" + players.get(i) + "]:$" + (totalVals[i].divide(BigInteger.valueOf(numRounds))));
            }
        } catch (Exception e) {
            System.err.println("An exception occured while running the controller.");
            e.printStackTrace();
        }
    }
    public static Random r = new Random(new Date().getTime());
    public static int getRandInt(int min, int max){
        return r.nextInt(max - min) + min;
    }
}

Compile this with java Controller.java and run from a directory containing a directory like below:
+-- resources
|   +-- config
|   +-- players
|       +-- Player1Folder
|           +-- Player1Program
|       +-- Player2Folder
|           +-- Player2Program

The file config should look something like this:
3
50
java&-cp&"TestPlayer"&Test1
python&daydreamer/daydreamer.py
java&-cp&"DayTrader"&DayTrader

First number is number of rounds, second number is turns per round, followed by the commands to run each player.
Replace spaces with ampersands! ('&')
~Let me know if I can improve the wording of this post at all, and happy trading!

It seems that the long-term trend in a busy market will see the share have a negative value.

Price cannot go below 1. Forgot to mention that.

I'm not so sure prices will fall. Players can only buy, not sell, in the first round, right?

@xnor you can only sell shares if you own them, the controller checks this, and since the round starts you with 0 shares, you don't have any to sell. If you try to sell more than what you own it is effectively the same as skipping the turn.

What happens if you buy more than you can afford? Your very own Test1 program, included in the challenge, does not check for this. It just blindly tries to buy 10 shares.

@Rainbolt Controller does a check, and if you can't afford the number you requested, it doesn't sell you any and you effectively skip your turn. My test program is very rudamentary, it willingly skips its turn until it can buy 10 at a time.

@xnor, every share bought increases the price by an average of 3, and every share sold decreases it by an average of 3.5. In the long term in a busy market, the total number of shares currently held will be less than 1/7 of the total number bought in the entire history.

What kind of OS will you be running this on? If it's Linux, can I create a system variable?

@BetaDecay It will be running on a fresh Ubuntu VM, so yah go ahead :)

@spocot Ah, cheers!

Hey, as part of the leaderboard, can you post the stock price?

You could make an accent pun and name this challenge "Stack Market".

Could you put your controller program on something like Github and include a link so that we can test at home?

Is there a way to indicate if it is the first move (or last move) so we could clear our storage?

$4713199930331196453 is a very large amount of money - is that an exponential growth rate?

Looking at the leaderboard, I think the game is currently flawed. E.g., start at $14/sh, buy 357 (own 357, $0 in bank). Choose random number (3). Price goes up by 3357 to $1085/sh. Next round. Sell all 357 shares (own 0, $387,345 in bank). Choose random number (3). Price goes down by 3357 to $14/sh. Next round. After two rounds, the price has not changed and your bank has increased 77x (similar but less dramatic results can be had with other starting random variables). I propose changing to for each transaction instead of for each share for more reasonable values.

agree with @tolos about the flaw. I propose that traders are given a number of shares to start with so that there isn't an inevitable share value increase after the first round. Otherwise, there is no way to disrupt traders using this strategy e.g. traders start with $5000 + 200 shares.

@Moop store the number 1 on disk and increment it on every turn. When the file doesn't exist (or the counter is on 151 if the file is still there from a previous run) its the first turn and when your counter gets to 150, its the last turn

@ryan I could imagine a bug or two could happen during the competition and then spocot would restart it and mess up the counting system.

@Moop (and to the OP) I would expect the text environment to be clean between trials.

I suggest to aggressively increase the number of rounds from 3 to 1000000 (or so) to rule out random effects.

In my eyes the minimum price of $1 is a strategic game fault. Any (float) value between $1 and $0 (inclusive) should be allowed as well. Once $0 is touched the price should be trapped at $0 (no escape == crash).

Suggestion for game improvement: To more realistically simulate the market, and prevent the runaway effects we are seeing, I propose that the price be changed after each share, not at day end. Order would be determined by randomly selecting a trader from all traders still attempting to buy or sell, after each share is bought or sold.

Or just build a real order book.

You should also support selling short, that way there is something to do in the first round besides buying.

The control program is made in Java. It creates a Process from a ProcessBuilder and passes in the data as args to your program. It then attaches a BufferedReader to the process in order to read the std output from the program. It checks the output to see if it matches 'S>amnt<' or 'B>amnt<'. If it does, it performs checks to make sure the operation is valid. If the operation is not valid or the trader's output does not match what it is looking for, it skips that trader's turn.

@ Everyone
I am in the process of redoing the money system to make exponential growth and market corruption from one trader preventable. I will post the code on github asap.

Ok, added Controller program to post. If anyone wants to suggest a better way to calculate something let me know.

Traders now start with a random num of shares between 20 and 30

Why start with a random num of shares?

Do the people who have already played a round start afresh or is it just the newcomers?

Notes: 1. People wanting to test under Linux will need to remove the double-quotes from the Java examples in the config file. 2. The market price changes aren't what's documented in the spec. 3. If Controller.getRandInt is intended to be able to return max then it's buggy. 4. MAX_RUNNING is pointless because there's no multi-threading. 5. The controller has no real error handling, so when TestPlayer starts dying because the stock price is too hard, the controller spams error messages to the console.

And where's the new leaderboard?

I've tidied up the code and done three runs.

@PeterTaylor The amount of money people are earning seems amazingly high...

@BetaDecay, the market is broken. It takes 4 turns for the share value to start bouncing between the two caps (1 and 2147483646).

I've created a chat to discuss how the market should be fixed

When's the next run going to be?

I've voted to close since despite attempts to rewrite the controller it appears there is still no way to judge the answers, and there is no meaningful leaderboard.

I present 'daydreamer', who is always asleep and forgets to buy or sell anything. He hopes that other players will have a net loss. Python code:
if __name__ == "__main__":
    print "W"

run with python daydreamer\daydreamer.py 120 5000 0 or whatever values you want.
I will post a more serious answer later, this is just to get the ball rolling :)

I don't think that will run - you need to indent the print.

Given that the stock price will tend to drop in the long run, not trading may be an excellent strategy.

A strange game: the only winning move is not to play. How about a nice game of chess?

DayTrader
Updated for rule change made on 8/21/2014, where players now start with 20-30 shares.
Buys as much as possible, then sells as much as possible.
Philosophy
We hope that the below pattern will repeat itself over and over. Note that by adhering to this pattern, we also contribute to it.

Everyone can only buy or hold on round one. The value can only increase, so we buy.
Everyone can buy more, hold, or sell on round two. We don't expect many players to buy on round two, so we sell.

The pattern is crystal clear at the beginning. Value will increase after round one. It should decrease after round two. Beyond that, projections get fuzzy. I expect to do well in the early rounds, before the market stabilizes.
import java.math.BigInteger;

/**
 * Submission for http://codegolf.stackexchange.com/q/36515/18487
 * @author Rainbolt
 */
public class DayTrader {

    /**
     * @param args the command line arguments containing the current
     * market value, our current money, and our current shares
     */
    public static void main(String[] args) {
        BigInteger marketValue = new BigInteger(args[0]);
        BigInteger myMoney = new BigInteger(args[1]);
        BigInteger myShares = new BigInteger(args[2]);

        // If we have less than or equal to 30 shares, buy as much as possible
        if (myShares.compareTo(new BigInteger("30")) <= 0) {
            System.out.println("B" + myMoney.divide(marketValue).toString());
        // Otherwise, sell as much as possible
        } else {
            System.out.println("S" + myShares.toString());
        }
    }

}

Compile with javac DayTrader.java. Run with java -cp "DayTrader" DayTrader.

Yay java! Makes it easier for me to run.

Your bot made market extend beyond the max number for integers, so I implemented BigIntegers into the code. Since everyone's code used ints, it crashed pretty much everyone's bot cept for the daydreamer

@spocot I edited my implementation to use BigInteger. Hopefully that helps.

I changed the max value for stocks to be the Integer max, but this still helps because the number of shares is technically limitless.

I think this is an inherent problem in the rules. If one trader gets like 140 shares he could control the market by himself. In two rounds he can buy shares for 10 each and sell them for 140 each, leading to a win of 1300% (assuming nobody does the opposite). This will escalate to something like 5000 * 13^25, which is way to big.

@spocot I just wanted to ping you because I modified my submission after your recent rule change.

Walt Disney - Python 3
Walt waits until the shares hit rock bottom and then buys as much as his money allows. Then, when the price soars, he sells them all.
Based upon Disney's strategy when he 'survived' through the Wall Street Crash. Unfortunately, my program cannot build theme parks... If only...
Run:
python3 waltdisney.py

Code:
from sys import argv
import os

price=int(argv[1])
money=int(argv[2])
share=int(argv[3])

if os.path.exists('./buyingprice.txt'):
    f = open('buyingprice.txt', 'r')
    buyingprice=int(f.read())
    f.close()
else:
    buyingprice=0

if share > 0:
    if price > buyingprice*10:
        print('S'+str(share))
    else:
        print('W')
elif money > 0:
    if buyingprice==0:
        print('B10')
        m=open('buyingprice.txt', 'w')
        m.write(str(price))
        m.close()
    elif price <= buyingprice:
        print('B'+str(int(money/price)))
        g=open('buyingprice.txt', 'w')
        g.write(str(price))
        g.close()
    else:
        print('W')

You're missing a closing parenthesis on your first print line.

@supersam654 Oh yeah, thanks

Can you point to a source for your assertion that Walt Disney actually used this strategy. Given there is a company named Walt Disney Co on the stock exchange it is difficult to search for, and Walt's wikipedia page doesn't mention it.

@Michael http://www.investopedia.com/articles/financial-theory/11/walt-disney-entertainment-to-empire.asp

@Michael I got the information originally from my history teacher, so sorry if the source is a bit weak.

Tommy
only knows what he has but is determined to risk everything on the market.  If he can buy, he will. If he can't, he sells everything he has so he can next turn. (This will work well with extreme ones like DayTrader but will autocorrect if the value drops when he thinks it will grow.)
import java.math.BigInteger;

public class Tommy {
    public static void main(String[] args) {
        BigInteger Value = new BigInteger(args[0]);
        BigInteger Money = new BigInteger(args[1]);
        BigInteger Shares = new BigInteger(args[2]);

       if (Money.compareTo(Value)<1) {
           System.out.print("S" + Shares.toString());
       } else {
           System.out.print("B" + Money.divide(Value).toString());
       }
    }

}

Golfscript
This is the same code but if prefered this.  I wrote the java after in case the BigInteger thing was needed. Use whatever is easier.
2$2$>{@@;;"S"\}{;\/"B"\} if

For future reference, all numbers in GS are big integers.

I guess I could have just posted the original without worrying about it then!  Good news.

I originally commented that I thought this was a duplicate of  DayTrader, but then I realized that the behavior is only the same because of circumstances, and that they could diverge under other circumstances. Sorry if I offended anyone. Let's get rich together!

@Rainbolt I wrote it GolfScript, read yours looking for duplicates before submitting, and actually used some or your code to write the Java version.  The core part is not a duplicate (or I wouldn't have submitted it) but ends up being simular in these volitile markets. I'm not offended but if you feel it is too close I will request it be disqualified (but the code remain, I learned something writing it which is the whole point).  As you have priority I wouldn't be offended even in that case. Note Earthquakers is almost identical to yours but does it differently (saves to file).

@kaine No no don't delete it. Like I said, I thought they were duplicates, but they definitely aren't. They are similar in behavior only because of the circumstances. I was wrong to post a comment claiming they were duplicates before I fully understood what yours was doing.

BuyAndHold - C
#include <stdio.h>
#include <stdlib.h>

/* BuyAndHold
 * Code revised from OptoKopper's WaitForCrash.c
 */
int main(int argc, char *argv[]) {
    long long int share_price = strtoll(argv[1], NULL, 0);
    long long int money = strtoll(argv[2], NULL, 0);

    if (money >= share_price) {
        printf("B%lld\n", money / share_price);
    } else {
        printf("W\n");
    }

    return 0;
}

Compile with: gcc buyandhold.c -o buyandhold
Run it with ./buyandhold PRICE MONEY SHARES

Haha I was hoping someone would complement DayTrader with a BuyAndHold. Well done!

Alfred Pennyworth - Python 2
While I was out on patrol one night, Alfred tried to create a stock trading program without my knowing. He thought he could hide it from me, but I found it and figured out what it did. Because I'm Batman. Now I've decided to enter it into a competition to teach him a lesson.
Money is no object to Alfred because I'm REALLY rich, but he's still smart about his trading. When he's out of shares, he buys as many as he can afford, regardless of market price. Then he sells 10 (or all remaining) shares every time the market price is higher than the price it was purchased at.
import argparse

parser = argparse.ArgumentParser(description="This is a private matter, Master Bruce. Learn how to make your own bed and I will tell you.")
parser.add_argument("Stuff", type=int, nargs='+', help="You don't need to know, Master Bruce.")

args=parser.parse_args()
vals=[]
for x in args:
    vals.append(x)

a=vals[0]
b=vals[1]
c=vals[2]

if c==0:
    x=1
    while x*a<b:
        x+=1
    print "B"+str(x)
    with open("lastval.txt", w) as f:
        f.write(a)

else:
    lastval=next(open("lastval.txt"))
    if a>lastval:print "S10" if c>10 else "S"+str(c)
    else:print 'W'

Run with: python GoAwayMasterBruce.py <args>

AttributeError: 'ArgumentParser' object has no attribute 'parseargs' Which version of Python does it need?

My mistake, there's an underscore. parse_args()

NaiveBot
NaiveBot is new to all this "stock market" hooplah. He just assumes that when the price is going up he should buy, and when the price goes down he should sell. But he's no sap, he's got a trick up his sleeve! He only ever buys half of what he can afford, and only ever sells half of what he has.
No more living in a box under the freeway for NaiveBot!
<?php
$cur = array('price' => $argv[1], 'funds' => $argv[2], 'shares' => $argv[3]);

$cachefile = 'cache.json';
if( ! file_exists($cachefile) ) { $cache = array(); }
else { $cache = json_decode(file_get_contents($cachefile), true); }

// determine action
if( empty($cache) ) {
    $action = 'buy'; // always buy on first turn
} else if( $cur['price'] > $cache[count($cache)-1]['price'] ) {
    $action = 'buy';
} else if( $cur['price'] < $cache[count($cache)-1]['price'] ) {
    $action = 'sell';
} else {
    $action = 'hold';
}

// determine volume
if( $action == 'hold' ) {
    $volume = 0;
} else if( $action == 'buy' ) {
    // spend half my money on shares!
    $volume = floor(($cur['funds']/2)/$cur['price']);
} else if( $action == 'sell' ) {
    // sell half my shares!
    $volume = floor($cur['shares']/2);
}

// do a thing!
if( $action == 'hold' ) { echo 'W'; }
else if( $action == 'buy' ) { echo "B $volume"; }
else { echo "S $volume"; }
echo "\n";

$cache[] = $cur;
if( count($cache) == 50 ) { unlink($cachefile); } // wipe cache on last turn
else { file_put_contents($cachefile,json_encode($cache)); } // write cache

Run with php Naivebot.php $1 $2 $3, makes a cache.json in its current folder.

Profit - Haskell

Wait until the price is 1/maxValue
Buy/Sell everything
????
PROFIT!!!

import System.Environment (getArgs)

main = putStrLn . trade . map read =<< getArgs

trade :: [Integer] -> String
trade [p,m,s] -- not intended
  | p == 1 = "B" ++ (show m)
  | p == (fromIntegral $ (maxBound::Int) - 1) = "S" ++ (show s)
  | otherwise = "W"

Compile with ghc profit.hs and run with ./profit price money stock.
If it is not efficient enough, add -O3 flag, although it probably is overkill :D

Edit:
"optimised", now sells everything when the price is equal to Integer.MAX_VALUE.

Why not main = putStrLn . trade . map read =<< getArgs ? Less noisy

@awashburn Because I am not that well read regarding monads ;)

I hope my comment helped you learn something new!

@ThreeFx there's a program for doing it, cabal install pointfree, now everyone will think you eat monads for breakfast.

@SeanD Thanks, I'll have a look at it

WaitForCrash
EDIT: fixed flaw in concept
EDIT: now using long long int
This is my first try. It behaves really simple and keeps one share to distinguish if it is the first round or a later one. In the first round nothing can be lost, so it buys shares. If it has shares it sells them. If eventually share prices drop to 10, it will buy again.
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    long long int share_price = strtoll(argv[1], NULL, 0);
    long long int money = strtoll(argv[2], NULL, 0);
    long long int shares_owned = strtoll(argv[3], NULL, 0);

    if(shares_owned > 1) {
        printf("S%lld\n", shares_owned - 1);
    } else if (shares_owned == 0 || share_price == 10) {
        printf("B%lld\n", money / share_price);
    } else {
        printf("W\n");
    }

    return 0;
}

compile with: gcc waitforcrash.c -o waitforcrash
run it as ./waitforcrash PRICE MONEY SHARES

Hope you don't mind I swiped your code to use as the basis for the BuyAndHold solution.  BTW with long long ints, %d needs to be %Ld to avoid warnings (or is it %lld? Neither gives me a warning).

It's okay. Yeah I had the %lld in my code, must have forgotten them in the update, ty.

IntelliTrader
1st round he will sell his shares if they're a good price: $80 or more.
Then he will sell off if the price is the same or better than the last price he sold at,
buy if the price is the same or lower than the last price he bought at.
IntelliTrader.java
import java.io.*;
import java.math.BigInteger;
import java.util.Properties;

public class IntelliTrader {

    private static final String ROUND_NUM = "roundNum";
    private static final String LAST_BUY = "lastBuy";
    private static final String LAST_SELL = "lastSell";
    private static final String FILE = "IntelliTrader/memory.txt";

    private Properties memory;
    private int roundNum;

    private IntelliTrader(Properties memory) {
        this.memory = memory;
        roundNum = new Integer(memory.getProperty(ROUND_NUM, "0"));
    }

    public String evaluate(BigInteger market, BigInteger money, BigInteger shares) {
        String command = "W";
        if (roundNum == 0) {
            if (market.intValue() > 80) {
                command = sell(market, shares);
            } else {
                command = buy(market, money);
            }
        } else {
            if (market.compareTo(new BigInteger(memory.getProperty(LAST_SELL, "0"))) >= 0) {
                command = sell(market, shares);
            } else if (market.compareTo(new BigInteger(memory.getProperty(LAST_BUY, "999999999"))) <= 0) {
                command = buy(market, money);
            }
        }
        return command;
    }

    private String buy(BigInteger cost, BigInteger money) {
        memory.setProperty(LAST_BUY, cost.toString());
        return "B" + money.divide(cost).toString();
    }

    private String sell(BigInteger cost, BigInteger shares) {
        memory.setProperty(LAST_SELL, cost.toString());
        return "S"+shares.toString();
    }

    public static void main(String[] args) {
        BigInteger marketValue = new BigInteger(args[0]);
        BigInteger myMoney = new BigInteger(args[1]);
        BigInteger myShares = new BigInteger(args[2]);

        Properties memory = new Properties();
        try {
            memory.load(new FileReader(FILE));
        } catch (IOException e) {
            //ignore, file probably doesn't exist yet
        }

        int roundNum = new Integer(memory.getProperty(ROUND_NUM, "0"));
        if (roundNum > 49) {
            roundNum = 0;
            memory.setProperty(ROUND_NUM, "0");
            memory.setProperty(LAST_BUY, "0");
            memory.setProperty(LAST_SELL, "0");
        }

        IntelliTrader it = new IntelliTrader(memory);
        String command = it.evaluate(marketValue, myMoney, myShares);
        System.out.println(command);

        roundNum++;
        memory.setProperty(ROUND_NUM, ""+roundNum);
        try {
            memory.store(new FileWriter(FILE), "IntelliTrader memory properties");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Compile with javac IntelliTrader. Run with java -cp "IntelliTrader" IntelliTrader

In my tests this seems to be the second best trader.

Earthquaker
Alternates between buying everything and selling everything (but one). It doesn't really aim to win as much as it does disrupt everyone else.
using System;
using System.IO;

namespace Earthquaker
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length < 3)
                return;

            int stockPrice = int.Parse(args[0]);
            int money = int.Parse(args[1]);
            int stocks = int.Parse(args[2]);

            bool shouldBuy = true;

            if (stocks != 0)
            {
                StreamReader sr = new StreamReader("brain.txt");
                if (sr.ReadLine() == "B")
                    shouldBuy = false;
                else
                    shouldBuy = true;
                sr.Close();
            }

            if (shouldBuy)
                Console.Write("B" + (money / stockPrice));
            else
                Console.Write("S" + (stocks - 1));

            StreamWriter sw = new StreamWriter("brain.txt", false);
            sw.Write(shouldBuy ? 'B' : 'S');
            sw.Close();
        }
    }
}

Compile with csc Earthquaker.cs. Run with Earthquaker.

.Net has System.IO.File.ReadAllText and WriteAllText, so you can simplify your history tracking slightly.

This crashes if it doesn't find its brain.txt file.

MonkeyTrader (in JAVA)
There's a saying that monkeys are good traders. I make the proof. Decisions between "buy" and "sell" are totally random.
import java.math.BigInteger;
import java.util.Random;

public class MonkeyTrader {
    /**
     * @param args the command line arguments containing the current
     * market value, our current money, and our current shares
     */
    public static void main(String[] args) {
        BigInteger marketValue = new BigInteger(args[0]);
        BigInteger myMoney = new BigInteger(args[1]);
        BigInteger myShares = new BigInteger(args[2]);
        Random random=new Random();

        switch (random.nextInt(2)) {
        case 0:
            System.out.println("B" + myMoney.divide(marketValue));
            break;
        case 1:
            System.out.println("S" + myShares);
            break;
        }
    }
}

 theAnswerOfLifeIs42.py
My program loves the number 42
The rule is simple: I can either buy 42 stock or sell 42 stock.
import sys
price, money, shares = [int(arg) for arg in sys.argv[1:]]

if money>42*price:
 print "B 42"
else:
 print "S 42"

LeesonLearnt v1.1 (Java, conservative)
Since the rule change means that we now start with some shares, there's no longer a guaranteed best first move, so I've simplified this by removing the special case for the first turn.
import java.math.BigInteger;

public class LeesonLearnt {
    private static final BigInteger THRESHOLD = new BigInteger("100");

    public static void main(String[] args){
        BigInteger price = new BigInteger(args[0]);
        BigInteger capital = new BigInteger(args[1]);
        BigInteger shareholding = new BigInteger(args[2]);

        BigInteger affordable = capital.divide(price);

        // In the long run, the shares will probably lose all their value.
        // But if they're cheap, buying them will pump them and they can be sold at a profit.
        // The target amount of our value held in shares varies exponentially with their price.
        BigInteger targetShareholding = price.compareTo(THRESHOLD) > 0
            ? BigInteger.ZERO
            : affordable.add(shareholding).shiftRight(price.intValue() - 1);
        if (targetShareholding.compareTo(shareholding) <= 0) {
            System.out.println("S" + shareholding.subtract(targetShareholding));
        }
        else {
            BigInteger diff = targetShareholding.subtract(shareholding);
            System.out.println("B" + diff.min(affordable));
        }
    }
}

Invoke as
java -cp LeesonLearnt LeesonLearnt <price> <capital> <shareholding>

Dollar Cost Averager - Python 3
This strategy attempts to use dollar cost averaging by buying (as close as it can to) a fixed amount of money (arbitrarily set at 150 so that it'll probably use up most of its money by the end) each turn.
import sys
price, money, shares = [int(arg) for arg in sys.argv[1:]]
target_per_day = 150
buy = round(min(target_per_day, money) / price)
if buy * price > money:
    buy -= 1
if buy > 0:
    print("B" + str(buy))
else:
    print("W")

Cash Is King - Python 2 or 3
This guy is very pessimistic about the stock market. He'd rather keep his money in cash where he can keep it safe under his mattress.
import sys
shares = int(sys.argv[3])
if shares > 0:
    print("S" + str(shares))
else:
    print("W")

Slow and Steady
As long as it has money, it buys $165 worth of shares. Otherwise it sells all of its shares to get more money, to buy more shares. On the 50th round it makes sure to sell all shares, because in the end we want cash.
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Paths;

public class SlowAndSteady{
    public static void main(String[] args) {
        BigInteger price = new BigInteger(args[0]);
        BigInteger cash= new BigInteger(args[1]);
        long shares= Long.parseLong(args[2]);
        BigInteger number = new BigInteger("165");
        String count = "0";

        try {
            count = new String(Files.readAllBytes(Paths.get("counter.txt")));
        } catch (IOException e) {

        }

        int c = Integer.parseInt(count)+1;

        if (c >= 50)
        {
            System.out.println("S" + shares);
            c=0;
        }

        else if(cash.compareTo(number) > 0)     System.out.println("B" + (number.divide(price)));

        else System.out.println("S" + shares);

        try {
            Writer wr = new FileWriter("counter.txt");
            wr.write(Integer.toString(c));
            wr.close();
        } catch (IOException e) {
        }
   }
}

Compile with javac SlowAndSteady.java. Run with java -cp "SlowAndSteady" SlowAndSteady. Counter should reset between rounds, but if the file is deleted, it will also work.

Time is Right - Python 3
I got bored so I wrote another entrant...
This young entrepeneur lives his life by the clock. When the time is right, he makes a decision. He also annoyingly uses French out of context... ;)
Run:
python3 timeisright.py [arg1] [arg2] [arg3]

Code:
import sys, time

price = int(sys.argv[1])
money = int(sys.argv[2])
shares = int(sys.argv[3])

lheure = int(time.time())

if lheure % 3 == 0:
    print('S'+str(int(shares/4)))
elif lheure % 3 == 1:
    print('B'+str(int(money/4*price)))
else:
    print('W')

BuyHighSellLow
Tracks the market history and buys when the price low and sells when it's high.
import sys

storage = 'BuyHighSellLow'
turn = 0
turns = 50
max_start_price = 150
limit = 0.25

price = int(sys.argv[1])
money = int(sys.argv[2])
shares = int(sys.argv[3])

# Calculate average price
with open(storage+'/history', mode='a') as f:
            pass # Create file if it doesn't exist
with open(storage+'/history', mode='r') as f:
    values = list((int(line) for line in f))
    turn = len(values) + 1
    if turn > turns: turn = 1
    if turn == 1:
            average = max_start_price + 1
            turn = 1
    else:
            average = sum((value / turn for value in values))

# Buy low and sell high
if price < average:
    print('B' + str(int(limit * money / price)))
elif price > average:
    print('S' + str(int(limit * shares)))
else:
    print('W')

# Save history
if turn == 1: mode='w'
else: mode = 'a'
with open(storage+'/history', mode=mode) as f:
    print(price, file=f)

Run with:
python3 BuyHighSellLow/buyhighselllow.py

Ol' Timer - Fortran 77
This old man is going to waste away his pension after sixty years of working as an office clerk. During his old age, however, he became quite blind, so he can only see he first number of each argument, so he estimates the price. His method is similar to that of Walt's, except Ol' Timer is a little more careless.
Because of the problems with the Fortran printing, I've written a Python program which will help. The program takes the arguments supplied and pipes them through to the Fortran program. Then, the Python program reformats the output to the expected format.
Compile:
gfortran oltimer.for -o oltimer.exe

Run:
python3 assistant.py [arg1] [arg2] [arg3]

Python Assistant Code:
from subprocess import Popen, PIPE
import sys, re

ret = Popen('./oltimer.exe '+sys.argv[1]+' '+sys.argv[2]+' '+sys.argv[3], stdout=PIPE, shell=True).communicate()[0].decode('utf-8')
value=re.findall(r'\d+',ret)

if 'W' in ret:
     print('W')

elif 'B' in ret:
     print('B'+str(value[0]))

elif 'S' in ret:
     print('S'+str(value[0]))

FORTRAN Main Code:
      PROGRAM OLTIMER
C DEFINE VARIABLES
          INTEGER :: PRICE
          INTEGER :: STOCK
          INTEGER :: MONEY
          INTEGER :: INTBUFFER
          CHARACTER :: BUFFER
C GET CMD ARGUMENTS & CONVERT TO INT
          CALL getarg(1, BUFFER)
          READ (BUFFER, '(i10)') PRICE
          CALL getarg(2, BUFFER)
          READ (BUFFER, '(i10)') MONEY
          CALL getarg(3, BUFFER)
          READ (BUFFER, '(i10)') STOCK
C EVALUATE SITUTATION AND MAKE DECISION
          IF (PRICE.LT.5) THEN
            IF (MONEY.GT.0) THEN
                INTBUFFER=(MONEY*50)/(5-PRICE)
                PRINT*,'B',INTBUFFER
            ELSE
                PRINT*,'W'
            END IF
          ELSE
            IF (PRICE.GT.9) THEN
                IF (STOCK.GT.0) THEN
                    INTBUFFER=STOCK/(PRICE-9)
                    PRINT*,'S',INTBUFFER
                ELSE
                    PRINT*,'W'
                END IF
            ELSE
                PRINT*,'W'
            END IF
          END IF
      END PROGRAM

Given that you need Python anyway, and that there are other answers in Python but none in Fortran, do you not think it would make sense to implement the whole thing in Python and reduce the burden of compilers which OP has to install?

@Peter I would but I thought it'd be fun to have a completely different language and see how it performs.

BuyAndSell - C
Similar but not a duplicate of Tommy.  Alternates between panic buying as much
as possible and selling everything.  Almost a duplicate of Earthquaker which retains one share while BuyAndSell sells all shares. BuyAndSell takes no action when it has no shares to sell but hasn't got enough money to buy one share.
/* BuyAndSell
 * Code revised from OptoKopper's WaitForCrash.c and my BuyAndHold.c
 * Alternates between buying as many shares as possible and selling everything
 * Run it as ./buyandsell PRICE MONEY SHARES
 */
int main(int argc, char *argv[]) {
    long long int share_price = strtoll(argv[1], NULL, 0);
    long long int money = strtoll(argv[2], NULL, 0);
    long long int shares = strtoll(argv[3], NULL, 0);

    if (money >= share_price) {
        printf("B%lld\n", money / share_price);
    } else {
        if (money == 0) {
            printf("S%lld\n", shares);
        } else {
            printf("W\n");
        }
    }

    return 0;
}

Compile with "gcc buyandsell.c -o buyandsell"
Run as "./buyandsell PRICE MONEY SHARES

Test1 Trader
public class Test1 {

    public static void main(String[] args){
        int marketValue = Integer.parseInt(args[0]);
        int myMoney = Integer.parseInt(args[1]);
        int myShares = Integer.parseInt(args[2]);

        //Buy 10 if we don't have any.
        if(myShares <= 0){
            System.out.println("B10");
        }else{
            System.out.println("S1");
        }
    }
}

Compile with javac Test1.java run with java -cp "Test1" Test1

Hedgehog - python2.7
This is mostly to reserve the name
from __future__ import print_function
from sys import argv

storage = 'prices.txt'
price,cash,shares = map(long, argv[1:])
turn = 1
buy = lambda x: print('B%d' % long(x))
sell = lambda x: print('S%d' % long(x))
cashtoshares = lambda c: long(c/price)
TURN,PRICE,CASH,SHARES=range(4)

try:
    data = [map(long, line.split()) for line in open(storage)]
    if data:
        turn = data[-1][TURN] + 1
except IOError:
    pass
with open(storage, 'a') as pricelist:
    pricelist.write('%d %d %d %d\n' % (turn, price, cash, shares))

if turn == 1:
    buy(cashtoshares(cash)) # convert all cash into shares
elif price == 1:
    buy(cashtoshares(cash)) # cannot buy at a better deal
elif price < 10:
    buy(cashtoshares(cash/2))
elif shares < 10:
    buy(cashtoshares(cash/2))
else:
    sell(shares/2)

Run as
python hedgehog.py PRICE CASH SHARES

Gorge Soros
price = ARGV.shift
money = ARGV.shift
stock = ARGV.shift
if price*10<money
  puts "B10"
else
  puts "S#{stock}"
end

Buys slowly, than sells everything in an attempt to crash the market.
Run with:Soros.rb price money stock

It explicitly says in the question text Do not intentionally create programs to crash the simulation.

@BetaDecay I meant dont try to crash the controller. Trying to crash the market is part of the game.

@spocot Oh, I thought that you meant to not create programs to crash the market. You should phrase that differently to prevent more confusion.


text:
Implement bit-wise matrix multiplication
The MMIX architecture is a fairly simple big-endian RISC design. It has a couple of interesting features, one of them is the MXOR instruction, which is what you should implement.
The MXOR instruction interprets its arguments (two 64-bit registers) as two 8×8 matrices of bits and performs a matrix multiplication where exclusive-or is used for addition and logical and is used for multiplication.
An argument in binary representation where the leftmost digit is most significant

a0 a1 a2 … a63

is interpreted as a matrix like this:

a0 a1 … a7
  a8 a9 … a15
  …
  a56 a57 … a63

Your task is to write a function, subroutine or similar in a language of choice which can be evoked from a single-letter name (i.e. f(x,y)) that implements this function. The two arguments of the function shall be of equal implementation-defined unsigned 64 bit integer type, the function shall return a value of the same type.
he winner of this competition is the shortest submission (measured in bytes or characters if the language you use uses a meaningful character encoding). You are encouraged to post a readable commented version of your code in addition to the golfed solution so other's can understand how it works.

Some test cases would be nice.

Do the input and outputs need to be numbers that correspond to the bitstrings, or can we use lists of bits?

Am I allowed to use the language's matrix multiplication (if present in the standard lib)?

Put another way, matrix multiplication where the elements of the matrix are in GF(2).

@Howard: why not?

@FireFly Please do not alter the specification without asking and without understanding what it's intent is.

APL, 28 characters
f←{2⊥,↑≠.×/{8 8⍴(64⍴2)⊤⍵}¨⍵}

Usage:
> f 12345678 87654321
3977539

You can read it almost literally if you go right-to-left. (64⍴2)⊤ transforms each argument into 64 bit representation and 8 8⍴ makes an 8x8 matrix out of the results. ≠.×/ then applies the inner product to both arguments, where multiplication × and xor ≠ is used. The matrix is then transformed back to vector form ,↑, before 2⊥ undoes the basis transformation.

Save 6 bytes by converting to tradfn, swapping ⊤'s arguments using ⍨, and flattening with ∊. Also, you don't need to count the naming of your function in your code length. Try it online!

x86 machine code, 45 44 40 bytes
  40072c:       b1 08                   mov    $0x8,%cl
  40072e:       48 c1 c7 08             rol    $0x8,%rdi
  400732:       b5 08                   mov    $0x8,%ch
  400734:       48 0f 6e c6             movq   %rsi,%mm0
  400738:       0f d7 d0                pmovmskb %mm0,%edx
  40073b:       40 20 fa                and    %dil,%dl
  40073e:       7a 01                   jp     400741 <amul+0x15>
  400740:       f9                      stc
  400741:       48 11 c0                adc    %rax,%rax
  400744:       48 d1 c6                rol    %rsi
  400747:       fe cd                   dec    %ch
  400749:       75 e9                   jne    400734 <amul+0x8>
  40074b:       48 c1 ce 08             ror    $0x8,%rsi
  40074f:       fe c9                   dec    %cl
  400751:       75 db                   jne    40072e <amul+0x2>
  400753:       c3                      retq

The code uses two tricky moves.  The first is the pmovmskb intsruction which takes every 8th bit of an mmx register and packs them together into an integer register.  Very useful for extracting columns.  The second is the parity flag which is used to accumulate the dot product (the and/jp/stc combo).
Here's the expanded code with comments:
    # rowloop
    mov $8, %cl
1:
    rol $8, %rdi    # get next row of A into low 8 bits

    # columnloop
    mov $8, %ch
2:
    # extract first column
    movq    %rsi, %mm0
    pmovmskb    %mm0, %edx

    # dot with current row
    testb   %dil, %dl

    # shift result and add parity bit
    jp  3f
    stc
3:
    adc %rax, %rax

    # shift over columns of B
    rol %rsi

    dec %ch
    jne 2b

    # restore B
    ror $8, %rsi

    dec %cl
    jne 1b
    ret

Looks cool! Very neat solution.

The use of the parity bit is really ingenious though. Makes the solution so much easier.

BTW, you can replace xor %rax,%rax by xor %eax,%eax for one byte. The high byte is zeroed out automatically.  sub %eax,%eax might be even shorter.

You might also want to replace setnp %dl; lea (%rdx,%rax,2),%rax by jnp 1f; stc; 1:adc %rax,%rax if that improves the size (should bring one byte).

Oh yes, you can also replace dec %cl;jne 1b by loop 1b since %ch will always be zero when encountering this instruction.

And finally, you don't need to initialize %rax at all—we left shift it's contents 64 times anyway so all the old contents are cleared out.

Here is an updated version of the code: http://fuz.su/~fuz/src/golf/dotproduct.s

@FUZxxl: I incorporated your suggestions.  The only one I didn't do is the loop suggestion - it doesn't quite work.  If rcx contains high bits on entry, we loop way too many times.  It turns out the result is always correct because we recompute it over and over, but if bit 63 of rcx is set, termination takes a really long time.

Shouldn't mov $8,%cl clear the upper 32 bits of %rcx? Looping for up to about 2³² extra cycles isn't too bad—should be an extra 20 seconds top.

@FUZxxl: no, it doesn't.

GolfScript (49 48 45 chars)
This takes a completely different approach to my earlier GolfScript entry, so I think it wants a separate answer.
{0{1$M&16.?M/:K*3$K&M*&^@2/@M)/@}255:M*++}:f;

It's pure bit-bashing.
If we consider a as a series of matrix elements we get
a_00 a_01 a_02 a_03 a_04 a_05 a_06 a_07 a_10 a_11 ...

Similarly b. Now, c_ij = a_i0 & b_0j ^ a_i1 & b1j ^ ... ^ a_i7 & b7j. So by grouping over the common index we get
c =   (a_00 a_00 ... a_00 a_00 a_10 a_10 ...) & (b_00 b_01 b_02 ... b_07 b_00 b_01 ...)
    ^ (a_01 a_01 ... a_01 a_01 a_11 a_11 ...) & (b_10 b_11 b_12 ... b_17 b_10 b_11 ...)
    ^ ...
  =   (((a >> 7) & 0x0101010101010101) * 0xff) & (((b >> 56) & 0xff) * 0x0101010101010101)
    ^ (((a >> 6) & 0x0101010101010101) * 0xff) & (((b >> 48) & 0xff) * 0x0101010101010101)
    ^ ...

That's enough background to be able to explain the code:
{                 # Function declaration boilerplate; stack is a b
  0               # Accumulator for the result
  {               # Loop: stack holds a>>k b>>8k partial-sum
    1$M&          #   M holds 255 (see below); get (b>>8k) & 0xff
    16.?M/:K      #   Derive 0x0101010101010101 and store in K
    *             #   Multiply: stack is a>>k b>>8k partial-sum rhs-of-and
    3$K&M*        #   Similarly for a: add lhs-of-and to the stack
    &^            #   Do the pointwise multiplication and addition
    @2/@M)/@      #   Restore loop invariant with a>>=1 and b>>=8
  }255:M*         # Store 255 in M and execute the loop that many times
                  # 8 times suffices to get the correct result; after that b>>8k == 0 and the
                  # partial sum doesn't change. After 64 iterations, a>>k == 0
  ++              # So we can ditch their remnants by adding to the partial sum
}:f;              # Function declaration boilerplate

Thanks to Dennis for the observation that 16.? is equal to 2 64? (or 2.6??); since it's one char shorter, I've stolen it. Thanks to Howard for suggesting a 2-char improvement which became 48->45.

Now that's an interesting approach. Nice bit magic!

You can replace ;; with * since b>>64 is always zero.

If you directly calculate the result on the stack (instead of collecting terms in an array) you may even save one more char: {0{1$255:M&16.?M/:K*3$K&M*&^@2/@M)/@}8*+\;}:f;.

@Howard, good points both. It's even possible to save one more by shifting a far enough right to become zero.

CJam, 35 bytes
{2{GG#+2b1>8/\}*zm*{z{:&}%:^}%2b}:F

Try it online by pasting the following Code:
{2{GG#+2b1>8/\}*zm*{z{:&}%:^}%2b}:F;  " Define function and clear stack.              ";
12345678 87654321 F                   " Call function.                                ";

How it works
2{      " Do the following twice:                                                     ";
  GG#+  " Add 16 ** 16 = 2 ** 64 to the topmost integer on the stack.                 ";
  2b    " Convert it into an array of its digits in base two.                         ";
  1>    " Discard the first digit.                                                    ";
  8/    " Split into arrays of 8 digits.                                              ";
  \     " Swap the resulting array with the second topmost stack element.             ";
}*      " This converts two 64-bit integers into 8×8 matrices of its base 2 digits.   ";
zm*     " Transpose the second matrix and compute the cartesian product of both.      ";
{       " For each pair (one row of the first and one column of the second matrix):   ";
  z     " Transpose the array.                                                        ";
  {:&}% " For each array of the array, compute the logical AND of its elements.       ";
  :^    " Compute the logical XOR of the results.                                     ";
}%      " Note that ^ and & are addition and multiplication in GF(2).                 ";
2b      " Convert the array of base 2 digits into and integer.                        ";

8 ** 8 = 2 ** 24, surely?

Of course... G is 16, so it's a wrong comment for correct code. Thanks!

Nice trick, though. If I steal it, I can save 1 char.

GolfScript (65 chars)
{[{2.6??+2base(;8/\}2*zip 8*\{{.}7*}%]zip{zip{~&}%{^}*}%2base}:f;

This turns out to be similar to BeetDemGuise's Python solution, although it uses more zips and less eval.
Dissection:
{
  # Stack: a b (as integers)
  [                  # Start gathering into array for subsequent zip
    {                # Repeat twice:
      2.6??+2base(;  # Convert to 64 bits
      8/             # Break into an 8x8 matrix
      \              # Flip top of stack
    }2*
    # Stack: a b (as matrices)
    # Each cell of the matrix product needs a row of a and a column of b
    zip 8*           # Get 8 copies of columns of b, ordered
                     #   [col_0 col_1 ... col_7 col_0 col_1 ...]
    \{{.}7*}%        # Get 8 copies of rows of a, ordered
                     #   [row_0 row_0 row_0 ... row_7 row_7]
  ]                  # Gather into array
  zip                # Zip: each array entry is now an array [col_j row_i]
  {                  # Map each array item
    zip              # Pair up each bit from col_j with corresponding bit of row_i
    {~&}%            # Multiply the bits in each pair
    {^}*             # Add the products
  }%

  2base              # Convert back from an array of 64 bits to an integer
}:f;                 # Assign to f and don't leave a copy lying about on the stack

J, 50 chars
Here is a version that does not use J's built-in general matrix product conjunction ..
   f=:#.@,@:(|."1)@(~:/@:*"2 1"1 2|.)&(8 8$]#:~64#2:)

Testing (with 4×4 matrices)
   g=:#.@,@:(|."1)@(~:/@:*"2 1"1 2|.)&(4 4$]#:~16#2:)
   44584 g 28371
46550

And the matrices visualized, for manual verification.
   (4 4$]#:~16#2:)&.> 44584;28371;46550
┌───────┬───────┬───────┐
│1 0 1 0│0 1 1 0│1 0 1 1│
│1 1 1 0│1 1 1 0│0 1 0 1│
│0 0 1 0│1 1 0 1│1 1 0 1│
│1 0 0 0│0 0 1 1│0 1 1 0│
└───────┴───────┴───────┘

Exploded view
                                  &(             ) to each of the arguments,
                                            64#2:    generate 64 2's (radix for below)
                                        ]#:~         decode from radix
                                    8 8$             reshape as 8×8 array
                (              |.)                 reverse the right argument
                       "2 1"1 2                    for each pair of rows,
                      *                              multiply
                    @:                               composed with
                 ~:/                                 xor folded
         (|."1)@                                   reverse each row
      ,@:                                          ravel (flatten array)
   #.@                                             back to binary again
f=:                                                assign function to name 'f'

Instead of 64#2:, isn't there a shorter construct with 64$2?

@FUZxxl no, we can substitute # with $ (they do the same in this case), but we need the 2 to be a verb for the whole paren to be a train. 2: is a constant verb returning 2.

A, right. That makes sense.

Python 2 - 183
def m(a,b):a,b=map(lambda x:'{:064b}'.format(x),[a,b]);r=range(8);return int(''.join(`eval('^'.join(o+'&'+t for o,t in zip(a[8*i:8+8*i],v)))`for i in r for v in[b[j::8]for j in r]),2)

This is the first thing that came to my mind and so it can mostly likely be golfed down quite a bit more. In any case, its pretty straight-forward string manipulation:
def m(a,b):
    # Convert the integer inputs to their 64bit binary versions.
    a,b=map(lambda x:'{:064b}'.format(x),[a,b])

    n=''
    # For all rows in matrix a...
    for row in [a[8*i:8+8*i] for i in range(8)]:
        # For all columns in matrix b...
        for col in [b[j::8] for j in range(8)]:
            # Get each pair.
            pairs = zip(row, col)

            # Multiply each pair.
            mul_pairs = ['&'.join(z) for z in pairs]

            # XOR them all together.
            result = '^'.join(mul_pairs)

            # Append the result to n.
            n+=`eval(result)`

    return int(n,2)

J (34)
This should work I think. It would be nice if you gave some test cases...
f=:~:/ .*&.(8 8&$@(_64&{.) :.,@#:)

This works with the test cases supplied in the comments (when changing 8 8 to 4 4 and changing 64 to 16)
Explanation
The whole function can be simplified to the following:
F&.G

Visual representation:

What this means: G is applied to both arguments. Then F is applied with G x as its left argument, and G y as its right argument. Then, the inverse of G is applied to the result of F. "Inverse?", you might ask. With inverse I mean a function applied _1 times, so for example the inverse of #: (dec -> bin vector) is #:^:_1 (or #.) (bin vector -> dec).
So, applying this theory, this would be G:

#: takes the binary form of the argument
_64&{. takes the last 64 items of the list. When there aren't 64 or
more items, it will be padded with 0's
8 8&$ shapes it to an 8*8 matrix
:., sets the reverse of (4 4&$@(_16&{.) to be just ,: ravel

and this would be F:

~:/ .* is matrix multiplication

Nope, I have a longer version using . that seems to work though.  You need to return the corresponding number of the matrix, and #: will have issues with leading zero bits. Also, the space before the . is significant (to disambiguate from /.). Oh, and you want ~: (xor) in place of + (or take the result modulo 2 manually).

@FireFly Made some changes, would that work?

Try these for testcases (4×4 arrays, so change the 8 8 correspondingly): 44584 × 33825 = 44584 (33825 is identity); 44584 × 28371 = 46550.

What I have is currently f=:#.@,@(~:/ .*)&(8 8$]#:~64#2:), but it's so similar to yours that it'd be weird to post it as its own answer.  Maybe you can work off of that.

It would be nice if you could add some text that explains how it works.

@FUZxxl Done!

I think you can shorten this using
8 8&$ :.,@(64#2)&#: for the right-hand side.